Synchronization primitives in the .NET Framework: which one is the good one? Synchronization primitives in the .NET Framework: which one is the good one? multithreading multithreading

Synchronization primitives in the .NET Framework: which one is the good one?


Albahari's book is amazing, you should really read through it some time. Its grown alot lately!

What you want

You want an EventWaitHandle (EWH), they are nice because there is nothing to pass around, they are used for signaling threads (either in the same or in a different process) and as the name implies, they can be waited on.

How you use it

You would open one on the thread that is doing the waiting, you open it with a given name that the other thread is going to know about. Then you wait on that wait handle.

The signaling thread will open an existing wait handle of the same name (name is a string) and call set on it.

Differences

AutoResetEvents and ManualResetEvents both inherit from EWH and they are really just EWH's, they just act differently. Which one you want just depends on if you want the EWH to act as a gate or a turnstyle. You only care about this if you are using the wait handle more than once or you are waiting on that wait handle by more than one thread. I've used wait handles a decent amount (I suppose) and I don't think I've ever used a Manual.

Important to know

  • Whatever you do, dont pass an instance of a wait handle around, they are meant to be opened seperately by their own threads. The name you specify will ensure that they are the "same" wait handle.

  • If the threads are in different processes, then you will HAVE to prefix the name of the EWH with @"Global\", otherwise the names of the wait handles will be encapsulated within the same process. Alternatively, if you are using them all within the same process, dont use the global namespace. When you don't specify a prefix with a backslash, one is automatically added to keep it private, but you don't need to know that prefix.

  • Keep in mind that EWH's can be permissioned, and if you run into issues with that I reccomend that you use EventWaitHandleRights.FullControl, but you can browse the full EventWaitHandleRights enumeration here.

  • I like to name my EWH's with a Guid.NewGuid().ToString("N") (Guid.NewGuid & Guid.ToString). I typically do this when the signaling thread is created, since you can easily pass information to it at that time. So in that case, the initial thread creates the string and passes it to the signaling thread when its created. That way both threads know of the name, without having to do any fancy cross-thread passing of variables.

  • EWH implements IDisposable so wrap it in a using block

Race conditions

EWH's are nice because if for whatever reason the signaling thread opens and signals the wait handle before the waiting thread even creates it, everything will still work and the waiting thread will be signaled the instant it hits the wait.

Because of this, though, the thread that is waiting on it will need to have some error trapping because you will need to call OpenExisting. If you call one of the ctor's and the EWH is already opened, you'll get a UnauthorizedAccessException or a WaitHandleCannotBeOpenedException thrown as described here, under Exceptions. You'll still be able to open that EWH and get the functionality you need, you may just have to open it instead of create it.


The difference between an auto-reset event and a manual-reset event is that an auto-reset event clears itself (closes) after one use, so only one item gets through the gate. I suspect an AutoResetEvent would do nicely here. Personally I tend to use Monitor more, though - it has lower overheads, but you do need to be a bit careful; your first thread must be sure to own the lock before any of the others, i.e

object lockObj = new object();lock(lockObj) {    // start the workers, making lockObj available to them    Monitor.Wait(lockObj);}

with the workers doing something like:

// lots of work// now signallock(lockObj) Monitor.Pulse(lockObj);// other work

Holding the lock originally means that we don't miss any messages while we are spinning up workers, as any workers getting to lock(lockObj) will be blocked until the original thread releases the lock at Monitor.Wait. The first thread the Pulse will signal our original thread to continue.


There is a great free e-book on this topic (and check part 2)

For what to use and when, there are many topics about this on SO, like this one: What is the difference between ManualResetEvent and AutoResetEvent in .NET?, to quote Dan Goldstein:

"Yes. It's like the difference between a tollbooth and a door. The ManualResetEvent is the door, which needs to be closed (reset). The AutoResetEvent is a tollbooth, allowing one car to go by and automatically closing before the next one can get through."