Thread WaitHandle on one topic

My code

public static void Invoke(Action[] Actions) { Thread[] threadArray = new Thread[Actions.Length]; for (int i = 0; i < Actions.Length; i++) { threadArray[i] = new Thread(() => { Actions[i].Invoke(); }); threadArray[i].Start(); } } public static void WaitAll() { } public static void WaitAny() { } 

I want to wait for the completion of all threads, and also get a notification when any thread is completed,

like WaitAny , WaitAll

But waithandles can only be used in threadpools, could not find examples for use in a single thread.

My application requires a lot of threads, hundreds of them, theadpool has the maximum thread limit, waiting tasks are queued.

How do I manage this?

UPDATE: here is the code, please let me know if a better code is possible.

 public class ParallelV2 { static int waitcount = 0; static WaitHandle[] waitHandles; public static void Invoke(Action[] Actions) { waitcount = Actions.Length; Thread[] threadArray = new Thread[Actions.Length]; waitHandles = new WaitHandle[Actions.Length]; for (int i = 0; i < Actions.Length; i++) { var count = i; waitHandles[count] = new AutoResetEvent(false); threadArray[count] = new Thread(() => { Actions[count].Invoke(); ((AutoResetEvent)waitHandles[count]).Set(); }); threadArray[count].Start(); } } public static void WaitAll() { while (waitcount > 0) { WaitHandle.WaitAny(waitHandles); waitcount--; } } public static void WaitAny() { WaitHandle.WaitAny(waitHandles); } } 
+4
source share
2 answers

In the example below, I had three threads that I needed to track. Each thread, when this has been done, will set a corresponding descriptor.

Declare it as follows:

 private WaitHandle[] waithandles; // see comment on static below 

Create it as follows:

 waitcount = 3; waithandles = new WaitHandle[3] { new AutoResetEvent(false), new AutoResetEvent(false), new AutoResetEvent(false) }; 

In the thread, when it is finished, set it like this:

 ((AutoResetEvent)waithandles[i]).Set(); 

(Actually, this is too simplistic, but it will work if you make waithandle static. What I actually did is a thread that calls back at the end of my life to signal waithandle)

In the main thread check this out. When the wait reached zero, I knew that all threads completed

 while (waitcount > 0) { WaitHandle.WaitAny(waithandles, 30000); waitcount--; } 
+4
source

You can wait until the end of the myThread with myThread.Join() .

+3
source

All Articles