Reputation: 5968
I have a C#/.Net application.
I use Monitor.Enter
and Monitor.Exit
to acquire exclusive access on some object to synchronize threads.
I have a specific case where a thread 1 should acquire exclusive access on some object. Another thread 2 should behave as follows: if there is no exclusive lock on the object, it should continue without acquiring exclusive lock. If there is already an exclusive lock acquired by another thread, it should wait until it's released.
I have been looking in the documentation here.
But I couldn't find any function that does this. Is that possible?
Upvotes: 1
Views: 198
Reputation: 1062770
So:
I believe that is achieved by simply:
lock (theThing) {}
This acquires and releases, which has the same semantics as not taking the lock, but waiting for anyone who does hold it.
Note that there is inherently a race condition in what you ask, as if you're not taking the lock: someone else could after you've checked. We long as that is OK.
There are also a myriad of methods on Monitor
for other scenarios, usually mixed with try
/finally
- in particular, TryEnter
with a zero timeout can be used for "take the lock immediately if you can, but don't wait if you can't".
However, a ManualResetEvent
may also be worth investigating.
Upvotes: 2