Thomas Carlton
Thomas Carlton

Reputation: 5968

How to use Monitor in threading without exclusive lock?

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

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062770

So:

  • if the object is currently locked, you wish to wait for it to be released, but not take the lock
  • if the object is not currently locked, you wish to continue without holding the lock

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

Related Questions