Wait until all threads finished their work in ThreadPool

后端 未结 5 450
不知归路
不知归路 2020-12-09 10:28

i have this code:

var list = new List();
for(int i=0;i<10;i++) list.Add(i); 
for(int i=0;i<10;i++)
{
     ThreadPool.QueueUserWorkItem(
             


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-09 10:39

    You'll need to track this yourself.

    One option for this is to use a counter and a reset event:

    int toProcess = 10;
    using(ManualResetEvent resetEvent = new ManualResetEvent(false))
    {
        var list = new List();
        for(int i=0;i<10;i++) list.Add(i); 
        for(int i=0;i<10;i++)
        {
            ThreadPool.QueueUserWorkItem(
               new WaitCallback(x => {
                  Console.WriteLine(x);  
                  // Safely decrement the counter
                  if (Interlocked.Decrement(ref toProcess)==0)
                     resetEvent.Set();
    
               }),list[i]);
        } 
    
        resetEvent.WaitOne();
    }
    // When the code reaches here, the 10 threads will be done
    Console.WriteLine("Done");
    

提交回复
热议问题