Check progress of multiple BackgroundWorker

2019-05-28 10:12发布

问题:

So I create multiple BackgroundWorkers using loop:

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

Now I just can't figure how do I check that all those workers finished their job ?

Thanks.

回答1:

You may keep a list of active workers and let each worker remove itself when finished:

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; }
}

If you don't want to pool IsWorkDone, you could raise an event after workers.Remove(worker) if list is empty...



回答2:

Assuming workers is the variable representing list of workers and _completedWorkersCount is the count of workers that have finished their job ....

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