Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoResetEvent, ManualResetEvent vs Monitor

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 single one of those more performant than the others?

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

like image 380
angrifel Avatar asked Nov 11 '09 18:11

angrifel


1 Answers

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.

like image 166
haze4real Avatar answered Nov 03 '22 21:11

haze4real