In the process of using multithreading, it may be encountered in some cases that the main thread must wait until all the child threads are executed before proceeding to the next step.
The following methods are as follows:
//In the process of using multi-threading, you may encounter in some cases that you have to wait until all the child threads are executed before the main thread will proceed to the next step. The method is as follows List<ManualResetEvent> manualEvents = new List<ManualResetEvent>();//Create thread waiting for collection for (int i = 0; i < 64; i++) //The number of WaitHandles must be less than or equal to 64, so the maximum number of threads is 64 { MB m = new MB();//Custom class, used to pass parameters = new ManualResetEvent(false); = i; (); (ThreadMethod, m); } (());//Waiting for all threads to end ("Thread Finished!");
private static void ThreadMethod(object obj) { MB m = (MB)obj; (1000);//Wait for 1 second to simulate the system handling things ();//Set the event to terminate ("Thread execute:" + ); }
When processing the above method, the number of threads exceeds 64, the number of WaitHandles must be less than or equal to 64, so the maximum number of threads is 64.
The solution is as follows:
using (var countdown = new MutipleThreadResetEvent()) { for (int i = 0; i < ; i++) { //Open N threads and pass the MutipleThreadResetEvent object to the child thread Param p = new Param(); = countdown; = pa[i]; (MyHttpRequest, p); } //Waiting for all threads to complete execution (); }
public class MutipleThreadResetEvent: IDisposable { private readonly ManualResetEvent done; private readonly int total; private long current; /// <summary> /// Constructor /// </summary> /// <param name="total">Total number of threads to wait for execution</param> public MutipleThreadResetEvent(int total) { = total; current = total; done = new ManualResetEvent(false); } /// <summary> /// Wake up a waiting thread /// </summary> public void SetOne() { // Interlocked atomic operation class, here to reduce the counter by 1 if ((ref current) == 0) { //When the waiting thread is completed, wake up the waiting thread (); } } /// <summary> /// Wait for so the thread is executed /// </summary> public void WaitAll() { (); } /// <summary> /// Free up space occupied by the object /// </summary> public void Dispose() { ((IDisposable)done).Dispose(); } }
The above is the detailed content of the example of C# multi-threading waiting for all child threads to end. For more information about C# multi-threading waiting for the end of child threads, please pay attention to my other related articles!