Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait until all threads finished their work in ThreadPool

Tags:

c#

threadpool

i have this code:

var list = new List<int>();
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);  
         }), list[i]);
} 

And i want to know when all threadpools threads finished their work. How i can to do that?

like image 648
Neir0 Avatar asked Mar 25 '10 23:03

Neir0


People also ask

When should you not use ThreadPool?

Thread pools do not make sense when you need thread which perform entirely dissimilar and unrelated actions, which cannot be considered "jobs"; e.g., One thread for GUI event handling, another for backend processing. Thread pools also don't make sense when processing forms a pipeline.


1 Answers

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<int>();
    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");
like image 125
Reed Copsey Avatar answered Oct 22 '22 17:10

Reed Copsey