Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monitor.Enter and Monitor.Exit in different threads

Monitor.Enter and Monitor.Exit are designed to be called from the same thread. But, what if I need to release a lock in a different thread than acquired?

For example: there are shared resource and asynchronous operation that uses this resource. The operation begins with BeginOperation and acquires the lock on the shared resource. There also the EndOperation method that releases the lock. EndOperation is typically called in another thread from a callback, thus I can't call Monitor.Exit in the EndOperation method. What is the best approach in this case? Will double-check locking with AutoResetEvent instead of Monitor be a good solution?

like image 283
eigenein Avatar asked Jun 12 '12 17:06

eigenein


People also ask

Does Monitor enter wait?

Wait is the same as Monitor. Enter except that it releases the lock on the object first before reacquiring.

How is lock different from Monitor in C#?

CSharp Online Training Both Monitor and lock provides a mechanism that synchronizes access to objects. lock is the shortcut for Monitor. Enter with try and finally. Lock is a shortcut and it's the option for the basic usage.

What does C# lock do?

C# Lock keyword ensures that one thread is executing a piece of code at one time. The lock keyword ensures that one thread does not enter a critical section of code while another thread is in that critical section. Lock is a keyword shortcut for acquiring a lock for the piece of code for only one thread.

What is a Monitor lock?

A lock typically prevents more than one entity from accessing a shared resource. Each object in the Java language has an associated lock, also referred to as a monitor, which a thread obtains by using a synchronized method or block of code.


Video Answer


1 Answers

The primitive you're looking for is called a semaphore which can be safely entered on one thread and exited from another.

like image 166
Yaur Avatar answered Oct 25 '22 13:10

Yaur