Multithreading when locking the main thread

How can I start 2 or more threads at the same time and block the main thread until the rest of the threads are completed?

+3
source share
4 answers

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

(EDIT: you have now indicated C #, there is no need for an agnostic platform 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 Joinif you only want to wait until they all end. (If you want to continue when any of them is finished, you need to get into the realm of waiting teams.)

+11
source
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);

}

, , - , , , . . BeginInvoke - , .

+2

Wintellect's Jeffrey Richter has a download library called the Power Threading library. I have not used it myself, but it can be useful.

0
source

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


All Articles