Spawn Multiple Threads for work then wait until all finished Spawn Multiple Threads for work then wait until all finished multithreading multithreading

Spawn Multiple Threads for work then wait until all finished


My preference for this is to handle this via a single WaitHandle, and use Interlocked to avoid locking on a counter:

class Program{    static void Main(string[] args)    {        int numThreads = 10;        ManualResetEvent resetEvent = new ManualResetEvent(false);        int toProcess = numThreads;        // Start workers.        for (int i = 0; i < numThreads; i++)        {            new Thread(delegate()            {                Console.WriteLine(Thread.CurrentThread.ManagedThreadId);                // If we're the last thread, signal                if (Interlocked.Decrement(ref toProcess) == 0)                    resetEvent.Set();            }).Start();        }        // Wait for workers.        resetEvent.WaitOne();        Console.WriteLine("Finished.");    }}

This works well, and scales to any number of threads processing, without introducing locking.


I like @Reed's solution. Another way to accomplish the same in .NET 4.0 would be to use a CountdownEvent.

class Program{    static void Main(string[] args)    {        var numThreads = 10;        var countdownEvent = new CountdownEvent(numThreads);        // Start workers.        for (var i = 0; i < numThreads; i++)        {            new Thread(delegate()            {                Console.WriteLine(Thread.CurrentThread.ManagedThreadId);                // Signal the CountdownEvent.                countdownEvent.Signal();            }).Start();        }        // Wait for workers.        countdownEvent.Wait();        Console.WriteLine("Finished.");    }}


If you have more than 64 wait handles for an STA Thread as Mark says. you could create a list with your threads and wait for all to complete in a second loop.

//check that all threads have completed.foreach (Thread thread in threadList){     thread.Join();}