Monitor.Enter and Monitor.Exit in different threads

Monitor.Enter and Monitor.Exit are for calling from the same thread. But, what if I need to release the lock in a different thread than the received one?

For example: there is a shared resource and an asynchronous operation that uses this resource. The operation starts with BeginOperation and gets a lock on the share. There is also an EndOperation method that releases the lock. EndOperation usually called on another thread from the callback, so I cannot call Monitor.Exit in the EndOperation method. What is the best approach in this case? Would it be good to check the lock with AutoResetEvent instead of Monitor ?

+7
source share
3 answers

Try using ManualResetEvent, it is used to block thead (s) until any external event occurs. MSDN Doc:

http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx

+4
source

The primitive you are looking for is called semaphore , which can be safely entered into one thread and exit another.

+11
source

If you can use .NET 4.0, you can replace it with System.Threading.Semaphore , which allows you to acquire permissions in one thread and release them in another.

The Semaphore class does not apply a thread identifier to WaitOne or Release calls.

+7
source

All Articles