Simple multithreaded question

Ok, I should have known the answer, but ...

I want to perform several different tasks in parallel on a separate thread and wait for all threads to complete before continuing. I know that I could use ThreadPool.QueueUserWorkItem() or BackgroundWorker , but did not want to use any (for no special reason).

So, is the code below the correct way to execute tasks in parallel in the background thread and wait for the completion of their 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 had to be asked 100 times before thanks for your reply and patience.

+4
source share
3 answers

Yes, this is the right way to do this. But if SomeActionDelegate relatively small, then the overhead of creating 3 threads will be significant. That is why you should probably use ThreadPool anyway. Although it does not have the net equivalent of Join.

BackgroundWorker is mainly useful when interacting with a graphical interface.

+4
source

It's always hard to say what the β€œright” one is, but your approach works correctly.

However, using Join , the UI thread (if the main thread is the UI thread) will be blocked, so it freezes the user interface. If this is not the case, your approach is basically fine, even if it has different problems (scalability / number of simultaneous threads, etc.).

+1
source

if you are using (or will be using .Net 4.0), try using a parallel task library

+1
source

Source: https://habr.com/ru/post/1301326/


All Articles