For multiple threads wait, can anyone compare the pros and cons of using WaitHandle.WaitAll and Thread.Join?
For multiple threads wait, can anyone compare the pros and cons of using WaitHandle.WaitAll
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
WaitHandle.WaitAllhas a 64 handle limit so that is obviously a huge limitation. On the other hand, it is a convenient way to wait for many signals in only a single call.Thread.Joindoes not require creating any additionalWaitHandleinstances. And since it could be called individually on each thread the 64 handle limit does not apply.Personally, I have never used
WaitHandle.WaitAll. I prefer a more scalable pattern when I want to wait on multiple signals. You can create a counting mechanism that counts up or down and once a specific value is reach you signal a single shared event. TheCountdownEventclass conveniently packages all of this into a single class.Update:
The reason why you want to signal the event from the main thread is subtle. Basically, you want to treat the main thread as if it were just another work item. Afterall, it, along with the other real work items, is running concurrently as well.
Consider for a moment what might happen if we did not treat the main thread as a work item. It will go through one iteration of the
forloop and add a count to our event (viaAddCount) indicating that we have one pending work item right? Lets say theSpawnAsynchronousOperationcompletes and gets the work item queued on another thread. Now, imagine if the main thread gets preempted before swinging around to the next iteration of the loop. The thread executing the work item gets its fair share of the CPU and starts humming along and actually completes the work item. TheSignalcall in the work item runs and decrements our pending work item count to zero which will change the state of theCountdownEventto signalled. In the meantime the main thread wakes up and goes through all iterations of the loop and hits theWaitcall, but since the event got prematurely signalled it pass on by even though there are still pending work items.Again, avoiding this subtle race condition is easy when you treat the main thread as a work item. That is why the
CountdownEventis intialized with one count and theSignalmethod is called before theWait.