What is the main concept of WaitHandle?

What is the main concept of WaitHandle in a C # .net stream? What is its use? When to use it? How can I use the WaitAll and WaitAny methods ?

+46
multithreading c #
Mar 29 '10 at 13:10
source share
5 answers

Whenever you want to control the execution of multiple threads in your application. Although this does not only mean that only one thread increments the counter; but let the threads start / stop or stop at the event.

See WaitHandles - Auto / ManualResetEvent and Mutex

- EDIT -

WaitHandle is the mechanism that you use to control the execution of threads. It does not concern handles inaccessible in the stream; about its use in the stream.

It may be a thick example, but please bear with me; think, a lady gives five different tinted whistles to five girls and tells them to blow the whistle whenever something happens; The process for each girl whistles a whistle, and the lady finds out who blew the whistle.

Now, it’s not about sharing with each other, it’s possible for a lady to use them to “control” the execution or process of how the girls will whistle.

Thus, technically, the process will be as follows:

  • Create a wait event (ManualResetEvent object)
  • Register events, WaitHandle.WaitAny(events);
  • After you have completed the operation in your thread, .Set() , which tells WaitHandle that "I am done!".

For example, consider an example from the provided link. I added steps so you understand the logic. These are not rigidly formulated steps, but only what you can understand.

 class Test { static void Main() { //STEP 1: Create a wait handle ManualResetEvent[] events = new ManualResetEvent[10];//Create a wait handle for (int i=0; i < events.Length; i++) { events[i] = new ManualResetEvent(false); Runner r = new Runner(events[i], i); new Thread(new ThreadStart(r.Run)).Start(); } //STEP 2: Register for the events to wait for int index = WaitHandle.WaitAny(events); //wait here for any event and print following line. Console.WriteLine ("***** The winner is {0} *****", index); WaitHandle.WaitAll(events); //Wait for all of the threads to finish, that is, to call their cooresponding `.Set()` method. Console.WriteLine ("All finished!"); } } class Runner { static readonly object rngLock = new object(); static Random rng = new Random(); ManualResetEvent ev; int id; internal Runner (ManualResetEvent ev, int id) { this.ev = ev;//Wait handle associated to each object, thread in this case. this.id = id; } internal void Run() { //STEP 3: Do some work for (int i=0; i < 10; i++) { int sleepTime; // Not sure about the thread safety of Random... lock (rngLock) { sleepTime = rng.Next(2000); } Thread.Sleep(sleepTime); Console.WriteLine ("Runner {0} at stage {1}", id, i); } //STEP 4: Im done! ev.Set(); } } 
+47
Mar 29 '10 at 13:47
source share

WaitHandle is an abstract base class for two commonly used event handlers: AutoResetEvent and ManualResetEvent .

Both of these classes allow one thread to "signal" one or more other threads. They are used to synchronize (or serialize activity) between threads. This is done using the Set and WaitOne (or WaitAll ) WaitAll . For example:

Theme 1:

 // do setup work myWaitHandle.Set(); 

Theme 2:

 // do setup work myWaitHandle.WaitOne(); // this code will not continue until after the call to `Set` // in thread 1 completes. 

This is a very rudimentary example, and there are many of them available on the Internet. The basic idea is that WaitOne used to wait for a signal from another thread, which indicates that something has happened. In the case of AsyncWaitHandle (which returns when the delegate is invoked asynchronously), WaitOne allows you to force the current thread to wait until the async operation is complete.

If AutoResetEvent or ManualResetEvent not set, WaitOne calls will block the calling thread until the Set call is called. These two classes differ only in that AutoResetEvent "unsets" event, as soon as a successful WaitOne call completes, and subsequent calls are blocked until Set is called. ManualResetEvent must be explicitly disabled by calling Reset .

WaitAll and WaitAny are static methods of the WaitHandle class that let you specify the WaitHandles array to wait. WaitAll will be blocked until all provided descriptors are Set , while WaitAny will be blocked only until one of them receives Set .

+27
Mar 29 '10 at 13:45
source share

This is an abstract class, you are not using it directly. Specific derived classes are ManualResetEvent, AutoResetEvent, Mutex, and Semaphore. Important classes in your tool for implementing thread synchronization. They inherit the WaitOne, WaitAll, and WaitAny methods; you use them to detect that one or more threads have signaled a wait state.

A typical use case for Manual / AutoResetEvent is to instruct the thread to exit or transmit the signal of the thread that has passed to an important point in the sequence. A semaphore helps you limit the number of threads that perform an action. Or implement thread synchronization, which should not have an affinity for a specific thread. Mutex allows you to assign ownership of a piece of code to a single thread, and the lock operator is also often used there.

Books have been written about this. Joe Duffy Concurrent programming on Windows is the latest and greatest. Highly recommended if you plan to write threaded code.

+7
Mar 29 '10 at 13:32
source share

The idea behind the WaitAll and WaitAny methods is that they are useful when you have many tasks that you want to run in parallel.

For example, let's say you must complete a task that requires some processing for 1000 elements in an array that need to be processed in parallel. A typical Core 2 Duo + hyperthreading has only 4 logical processors, and therefore it doesn’t make much sense to have more than 4 threads running immediately (in fact, it’s true, but this is a story at another time - we will pretend and use the simple “one thread per processor” model "). Thus, 4 threads, but 1000 items; what do you do?

One option is to use the WaitAny method. You start 4 threads, and every time the WaitAny method returns you, you start from another until all 1000 elements are queued. Note that this is a bad example for WaitAny, as you can also just split your array into 250 element blocks. Hopefully, however, this gives you an idea of ​​the situation in which WaitAny is useful. There are other similar situations where WaitAny can make a lot of sense.

But now back to the scenario with 4 threads, each of which processes 250 elements from your array of 1000 units. With this option, you can use the WaitAll method to wait for all processing to complete.

+6
Mar 29 '10 at 13:20
source share

There are very long answers here. For those looking for a short answer:

Wait handle - a mechanism for creating one thread until another thread reaches a certain point.

You can also expect multiple threads and / or multiple threads waiting, therefore, the WaitOne , WaitAll and WaitAny . There are also several options for choosing semantics by choosing one of these classes: Mutex , Semaphore , ManualResetEvent , AutoResetEvent , which are well-documented.

0
Jun 29 '17 at 17:07 on
source share



All Articles