Check progress of multiple BackgroundWorker

放肆的年华 提交于 2019-12-12 10:13:54

问题


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


来源:https://stackoverflow.com/questions/10947384/check-progress-of-multiple-backgroundworker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!