开发者

Simple Multithreading Question

开发者 https://www.devze.com 2022-12-20 09:00 出处:网络
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 a

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 开发者_JAVA技巧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.


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号