18.9. Get the Naming Rights for Your Events
Problem
You want to have code running in worker threads, or in other processes or AppDomains, to be able to wait on an event.
Solution
Use the EventWaitHandle class. With it, you can create a named event that will allow any code running on the local machine to find and wait on the event. AutoResetEvent and ManualResetEvent are excellent for signaling events in threaded code and even between AppDomains if you are willing to go through the hassle of passing the event reference around. Why bother? Both of them derive from EventWaitHandle, but neither exposes the naming facility. EventWaitHandle can not only take the name of the event, but also can take an EventResetMode parameter to indicate if it should act like a ManualResetEvent (EventResetMode.ManualReset) or an AutoResetEvent (EventResetMode.AutoReset). Named events have been available to Windows developers for a long time, and the EventWaitHandle class can serve as a named version of either an AutoResetEvent or a ManualResetEvent.
To set up a named EventWaitHandle that operates as a ManualResetEvent, do this:
// Make a named manual reset event. EventWaitHandle ewhSuperBowl = new EventWaitHandle(false, // Not initially signaled EventResetMode.ManualReset, @"Champs"); // Spin up three threads to listen for the event. for (int i = 0; i < 3; i++) { Thread t = new Thread(ManualFan); // The fans wait anxiously... t.Name = "Fan " + i; t.Start( ); } // Play the game. Thread.Sleep(10000); // Notify ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access