views:

373

answers:

3

Lets say i have to orchestrate a synchronization algorithm in .net 3.5 SP1 and any of the synchronization primitives listed in the title fit perfectly for the task.

From a performance perspective, is any of those more performant than the other?

I ask this because I have been coding for a while now, but without proper knowledge on the subject.

Thanks.

+2  A: 

If you can, go with Monitor. It's similar to a CRITICAL_SECTION. AutoResetEvent/ManualResetEvent might have slightly more overhead, since these can be shared by different processes, whereas a Monitor belongs to a single process.

Gonzalo
Auto reset events are not shared between processes (mutexes are). But they are native Windows objects and you may run into trouble if you use too many of them.
Yann Schwartz
From http://msdn.microsoft.com/en-us/library/ms682400(VS.85).aspx looks like AutoReset can be shared too. At least there's nothing preventing you from creating an Auto event with a name but AutoResetEvent and ManualResetEvent do not let you pass a 'name'.
Gonzalo
Just use the baseclass EventWaitHandle. AutoResetEvent and ManualResetEvent are just constructor wrappers, the only thing they do is calling the constructor from EventWaitHandle either with EventResetMode.AutoReset or EventResetMode.ManualReset...
haze4real
+1  A: 

WaitHandles look very similar to Wait/Pulse Constructs, but the difference is in detail: The WaitHandles Set method, sets the Signal even if no thread is waiting. This means if you call Set in a thread and then call WaitOne in another thread on the same waithandle afterwards, the second thread will continue. Wait and Pulse are different, Pulse only signals a thread that is already in the waiting queue. This means if you call Pulse in a thread and then call Wait in another thread on the same object afterwards, the second thread will wait forever (deadlock). You've got to be extremely carefull if using Wait and Pulse, only use it if you know what you are doing otherwise you might just be lucky...

To create the behaviour of a WaitHandle yourself using Monitor, weather AutoReset or ManualReset, you've got to do way more than a simple Wait/Pulse Construct. Just use the Tools you need to get the Job done:

If you can't synchronize threads with simple locking or atomic operations, think of using WaitHandles. If you can't synchronize threads with WaitHandles, think of using Wait and Pulse.

haze4real
A: 
supercat