当前位置:网站首页>C# Monitor class
C# Monitor class
2022-08-02 23:37:00 【biyusr】
lock statement is parsed by the C# compiler to use the Monitor class.The following lock statement:
lock(obj){// synchronized region for obj}
is resolved to call the Enter() method, which waits until the thread locks the object.Only one thread can lock an object at a time, as long as the lock is released.The thread can then enter the synchronization phase.The Exit() method of the Monitor class releases the lock.The compiler puts the Exit() method in the finally handler of the try block, so if an exception is thrown, the lock is released.
Monitor.Enter(obj);try{// synchronized region for obj}finally{Monitor.Exit(obj);}
The main advantage of the Monitor class over C#'s lock statement is that you can add a timeout value for waiting to be locked.This way, instead of waiting indefinitely to be locked, the TryEnter() method can be used as in the example below, passing it a timeout value specifying the maximum time to wait to be locked.If obj is locked, the TryEnter() method sets the Boolean reference parameter to true and synchronously accesses the state locked by the object obj.If another thread locks obj for more than 500 milliseconds, the TryEnter() method sets the variable lockTaken to false, and the thread no longer waits, but is used to perform other operations.Maybe later, the thread will try to acquire the lock again.
bool _lockTaken = false;Monitor.TryEnter(_obj, 500, ref _lockTaken);if (_lockTaken){try{// acquired the lock// synchronized region for obj}finallycode>{Monitor.Exit(obj);}}else{// didn't get the lock, do something else}
边栏推荐
- 汉源高科2光12电千兆导轨式网管型工业以太网交换机双光自愈保护式以太网光交换机
- 【StoneDB性能相关工具】内存监控
- Day35 LeetCode
- 交 叉 数 组
- 模板的进阶
- EasyExcel dynamic parsing and save table columns
- .NET performance optimization - you should set initial size for collection types
- iframe------------frame-
- 太魔人招新啦|快来加入我们吧!
- Informatics Olympiad All-in-One (1257: Knight Moves)
猜你喜欢
随机推荐
【数据分析】:什么是数据分析?
Xcode13.1运行工程报错fatal error: ‘IFlyMSC/IFly.h‘ file not found的问题
C#异步和多线程
力扣每日一题-第46天-344. 反转字符串
李沐动手学深度学习V2-bert和代码实现
信息学奥赛一本通(1259:【例9.3】求最长不下降序列)
How to use windbg check c # a thread stack size?
TodoList案例
Implement fashion_minst clothing image classification
PG's SQL execution plan
9,共模抑制比一-不受输入信号中共模波动的影响。【如何分析共模CM抑制比。】
.NET性能优化-你应该为集合类型设置初始大小
The five classification of software testing
Which thread pool does Async use?
即时通讯开发移动端网络短连接的优化手段
Informatics Olympiad All-in-One (1260: [Example 9.4] Intercepting Missiles (Noip1999))
网上那么多教人赚钱的方法,但是你实际上是靠什么赚钱的呢?
软件成分分析:华为云重磅发布开源软件治理服务
WPF development through practical 】 【 automatic production management platform
太魔人招新啦|快来加入我们吧!







