c# - 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?
解决方案
所以:
- 如果对象当前被锁定,您希望等待它被释放,但不获取锁定
- 如果对象当前未锁定,您希望不持有锁定继续
我相信这可以通过简单地实现:
lock (theThing) {}
这将获取和释放,这与不获取锁具有相同的语义,而是等待任何持有它的人。
请注意,您所问的内容本质上存在竞争条件,就好像您没有获得锁定一样:在您检查后其他人可以。我们只要这样就可以了。
Monitor
对于其他场景还有无数种方法,通常与try
/混合使用finally
- 特别TryEnter
是零超时可用于“如果可以立即获取锁,但如果不能则不要等待”。
但是,aManualResetEvent
也可能值得研究。
推荐阅读
- java - 即使指定了选择参数,强制 Hibernate 始终使用默认的无参数构造函数
- xslt-2.0 - 对每个组使用 xslt
- networking - WNDR3800 运行 Gargoyle 1.11 网络配置 VLAN ID 设置时出错
- c++ - 多线程与 C++ 中的类
- c# - MVC Kendo Grid转换ToDataSourceResult耗时长,如何加快
- jira - ServiceDesk 通知中的混乱
- git - Bitbucket 使用 git-LFS 的最大 repo 大小
- angular - 动态设置 mat-tab 的背景颜色
- tensorflow - 从不同数据集中随机添加样本以检索最终数据集
- c++11 - Handling NULL while using std::move on the tuples