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(); } }
KMån Mar 29 '10 at 13:47 2010-03-29 13:47
source share