当前位置:网站首页>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}
边栏推荐
- "A daily practice, happy water problem" 1374. Generate a string with an odd number of each character
- go——内存分配机制
- 基于 outline 实现头像剪裁以及预览
- Flink Yarn Per Job - 创建启动Dispatcher RM JobManager
- Xcode13.1 run engineering error fatal error: 'IFlyMSC/IFly h' file not found
- 信息学奥赛一本通(1260:【例9.4】拦截导弹(Noip1999))
- 第一次进入前20名
- Thread线程类基本使用(下)
- C# Barrier class
- PyTorch分布式backends
猜你喜欢
随机推荐
PG's SQL execution plan
STP生成树协议
The Orsay in Informatics (1256: Bouquet for Algernon)
10 种最佳 IDE 软件 ,你更忠爱哪一个?
信息学奥赛一本通(1260:【例9.4】拦截导弹(Noip1999))
PyTorch分布式backends
golang 源码分析:uber-go/ratelimit
云平台简介
线程安全(上)
OpenCV开发中的内存管理问题
setup syntax sugar defineProps defineEmits defineExpose
信息学奥赛一本通(1259:【例9.3】求最长不下降序列)
信息学奥赛一本通(1256:献给阿尔吉侬的花束)
LeetCode 622 设计循环队列[数组 队列] HERODING的LeetCode之路
The time series database has been developed for 5 years. What problem does it need to solve?
PLC working principle animation
Day35 LeetCode
Axure9的元件用法
Flink Yarn Per Job - 启动AM
ShardingSphere-proxy +PostgreSQL implements read-write separation (static strategy)









