views:

128

answers:

3

Ok I should already know the answer but...

I want to execute a number of different tasks in parallel on a separate thread and wait for the execution of all threads to finish before continuing. I am aware that I could have used the ThreadPool.QueueUserWorkItem() or the BackgroundWorker but did not want to use either (for no particular reason).

So is the code below the correct way to execute tasks in parallel on a background thread and wait for them to finish processing?

Thread[] threads = new Thread[3];
for (int i = 0; i < threads.Length; i++)
{
    threads[i] = new Thread(SomeActionDelegate);
    threads[i].Start();

}

for (int i = 0; i < threads.Length; i++)
{
    threads[i].Join();
}

I know this question must have been asked 100 times before so thanks for your answer and patience.

+4  A: 

Yes, this is a correct way to do this. But if SomeActionDelegate is relatively small then the overhead of creating 3 threads will be significant. That's why you probaly should use the ThreadPool anyway. Even though it has no clean equivalent to Join.

A BackgroundWorker is mainly useful when interacting with the GUI.

Henk Holterman
+1  A: 

It's always hard to say what the "correct" way is, but your approach does work correctly.

However, by using Join, the UI thread (if the main thread is a UI thread) will be blocked, therefore freezing the UI. If that is not the case, your approach is basically OK, even if it has different problems (scalability/number of concurrent threads, etc.).

Lucero
A: 

if your are (or will be using .Net 4.0) try using Task parallel Library

TheOCD
Yep can't wait till .NET 4 is officially released
Kane