Wait for pooled threads to complete

后端 未结 9 653
无人及你
无人及你 2020-12-01 01:35

I\'m sorry for a redundant question. However, I\'ve found many solutions to my problem but none of them are very well explained. I\'m hoping that it will be made clear, he

9条回答
  •  囚心锁ツ
    2020-12-01 02:07

    Here is a solution using the CountdownEvent class.

    var complete = new CountdownEvent(1);
    foreach (var o in collection)
    {
      var capture = o;
      ThreadPool.QueueUserWorkItem((state) =>
        {
          try
          {
            DoSomething(capture);
          }
          finally
          {
            complete.Signal();
          }
        }, null);
    }
    complete.Signal();
    complete.Wait();
    

    Of course, if you have access to the CountdownEvent class then you have the whole TPL to work with. The Parallel class takes care of the waiting for you.

    Parallel.ForEach(collection, o =>
      {
        DoSomething(o);
      });
    

提交回复
热议问题