检查多个BackgroundWorker的进度

时间:2012-06-08 10:45:30

标签: wpf progress-bar backgroundworker

所以我使用循环创建了多个BackgroundWorkers:

  foreach (var item in list)
  {
    worker = new BackgroundWorker();
    worker.DoWork += worker_DoWork;
    worker.RunWorkerAsync(item);
  }

现在我无法想象如何检查所有这些工人是否完成了他们的工作?

感谢。

2 个答案:

答案 0 :(得分:2)

您可以保留一份活跃的工作人员列表,让每个工作人员在完成后自行删除:

List<BackgroundWorker> workers = new List<BackgroundWorker>();

...

  foreach (var item in list)
  {
    worker = new BackgroundWorker();
    worker.DoWork += worker_DoWork;
    workers.Add(worker);
    worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
    {
        BackgroundWorker worker = (BackgroundWorker)s;
        workers.Remove(worker);
    }
    worker.RunWorkerAsync(item);
  }

...

public bool IsWorkDone
{
    get { return workers.Count == 0; }
}

如果您不想集中IsWorkDone,如果列表为空,您可以在workers.Remove(worker)之后提出一个事件......

答案 1 :(得分:1)

假设workers是代表工人名单的变量,_completedWorkersCount是完成工作的工人数量....

    worker.RunWorkerCompleted +=
    (o, e) =>
     {
         _completedWorkersCount = workers.Where(w => !w.IsBusy).Count();
     };