Check progress of multiple BackgroundWorker

2019-05-28 09:21发布

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.

2条回答
放我归山
2楼-- · 2019-05-28 10:20

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...

查看更多
可以哭但决不认输i
3楼-- · 2019-05-28 10:23

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();
     };         
查看更多
登录 后发表回答