首页 > 解决方案 > 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 : I there is no exclusive lock on the object, it should continue without acquiring exclusive lock. I 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 please?

标签: c#multithreading

解决方案


所以:

  • 如果对象当前被锁定,您希望等待它被释放,但不获取锁定
  • 如果对象当前未锁定,您希望不持有锁定继续

我相信这可以通过简单地实现:

lock (theThing) {}

这将获取和释放,这与不获取锁具有相同的语义,而是等待任何持有它的人。

请注意,您所问的内容本质上存在竞争条件,就好像您没有获得锁定一样:在您检查后其他人可以。我们只要这样就可以了。

Monitor对于其他场景还有无数种方法,通常与try/混合使用finally- 特别TryEnter是零超时可用于“如果可以立即获取锁,但如果不能则不要等待”。

但是,aManualResetEvent也可能值得研究。


推荐阅读