Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use a WaitHandle instead of a lock

In C#, when we should use WaitHandle instead of lock ?

like image 433
Xaqron Avatar asked Dec 09 '22 09:12

Xaqron


2 Answers

A lock is fundamentally different from a WaitHandle. With a lock you write, for example:

lock (SomeResource)
{
    // do stuff here
}

The first line says, "I want exclusive access to that resource," and will wait until that resource is available (i.e. nobody else has a lock on it). Then the code runs and at the end the lock is released so that others can use it.

WaitHandle is used to wait for some event to take place. When you write:

MyWaitHandle.WaitOne();

Your code is waiting for some other thread (possibly in a different process) to signal that WaitHandle. What it signals could be anything. Perhaps you're waiting for another thread to finish its job and say, "I'm done now," before your code can continue.

So, to answer your question, you should use a lock when you want to gain exclusive access to a resource. You should use WaitHandle when you want to be notified of some event.

like image 191
Jim Mischel Avatar answered Dec 11 '22 21:12

Jim Mischel


When you need it. Seriously, lock is syntactic sugar with Monitor, which probably uses WaitHandles internally.

Only use it if you need more flexibility (like e.g. holding on to a lock longer than the current scope...) or manage multiple locks in the right order etc.

like image 39
sehe Avatar answered Dec 11 '22 21:12

sehe