views:

275

answers:

4

How do I start 2 or more threads all at once and block the main thread until the others threads are complete?

+9  A: 

From the main thread, call Thread.Join on each of the other threads.

(EDIT: Now you've specified C#, there's no need for the platform agnostic comment.)

For example:

Thread t1 = new Thread(FirstMethod).Start();
Thread t2 = new Thread(SecondMethod).Start();

t1.Join();
t2.Join();

It doesn't matter what order you call Join in, if you only want to wait until they've all finished. (If you want to continue when any of them have finished, you need to get into the realm of wait handles.)

Jon Skeet
In .NET 4.0 you may also get value out of using a System.Threading.CountdownEvent and calling 'Signal' on the child threads and 'Wait' on the main thread, or System.Threading.Barrier and call SignalAndWait on all three threads.
Rick
A: 

There's a good example of how to do threading in C# on MSDN

http://msdn.microsoft.com/en-us/library/aa645740%28VS.71%29.aspx#vcwlkthreadingtutorialexample1creating

If you look at the Mutex example it demonstrates putting the main thread to sleep until all child threads have completed.

Gwaredd
or Mutex example even ;)
Gwaredd
+2  A: 
public delegate void AsyncTask(object state);

public void Method1(object state) .....

public void Method2(object state) .....


public void RunAsyncAndWait(){

   AsyncTask ac1 = new AsyncTask(Method1);
   AsyncTask ac2 = new AsyncTask(Method2);

   WaitHandle[] waits = new WaitHandle[2];

   IAsyncResult r1 = ac1.BeginInvoke( someData , null , null );
   IAsyncResult r2 = ac2.BeginInvoke( someData , null , null );

   waits[0] = r1.AsyncWaitHandle;
   waits[1] = r2.AsyncWaitHandle;

   WaitHandle.WaitAll(waits);

}

This works, some people will aruge that if any of thread finishes first it will wait endlessly but I have tried, it have worked always. You can also give timeout to wait for. And in BeginInvoke first parameter is the value passed inside your methods.

Akash Kava
A: 

Jeffry Richter of Wintellect has a library for download called the Power Threading library. I have not used it myself but it might be helpful.

Loki Stormbringer