Kane
Kane

Reputation: 16812

Simple Multithreading Question

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.

Upvotes: 4

Views: 200

Answers (3)

TheOCD
TheOCD

Reputation: 161

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

Upvotes: 1

Lucero
Lucero

Reputation: 60276

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.).

Upvotes: 1

Henk Holterman
Henk Holterman

Reputation: 273804

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.

Upvotes: 4

Related Questions