开发者

When should I use a WaitHandle instead of a lock

开发者 https://www.devze.com 2023-03-01 08:28 出处:网络
In C#, when we should use WaitHandle开发者_运维百科 instead of lock ?A lock is fundamentally different from a WaitHandle. With a lock you write, for example:

In C#, when we should use WaitHandle开发者_运维百科 instead of lock ?


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.


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.


They accomplish completely different things. A lock is used to limit access to a specific block of code to a single thread at a time. A WaitHandle is the base class for several concurrency-related classes, such as Semaphore, Mutex, AutoResetEvent, and ManualResetEvent, which allow you to control concurrency in slightly different ways. For instance, a Semaphore allows you to limit concurrency to no more than N threads, instead of a single thread.


A WaitHandle can wait for multiple handles, a lock can wait for only one.


WaitHandle is often used when you have multiple threads running and you want to wait for one or all of them to complete before you continue to do some other action. lock would be used if you want to prevent multiple threads from accessing a shared resource at the same time.


The best explanation lies in these two links. Unfortunately you're going to have to do some reading to get a full answer to the type of question you asked:

This contains an example as well: http://msdn.microsoft.com/en-us/library/system.threading.waithandle.aspx

http://msdn.microsoft.com/en-us/library/kad9xah9.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号