当前位置:网站首页>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
}
finally
code>{
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
- Xcode13.1运行工程报错fatal error: ‘IFlyMSC/IFly.h‘ file not found的问题
- Common tools and test methods for interface testing (Introduction)
- 「每周译Go」这次我们来点不一样的!--《How to Code in Go》系列上线
- PLC工作原理动画
- Flink Yarn Per Job - 创建启动Dispatcher RM JobManager
- 接口测试常用工具及测试方法(入门篇)
- Qt提升自定义控件,找不到头文件
- STP生成树协议
- 数字孪生助力智慧城市可视化建设
猜你喜欢
随机推荐
网络协议介绍
A brief discussion on the transformation of .NET legacy applications
Digital twins help visualize the construction of smart cities
Qt提升自定义控件,找不到头文件
基本语法(三)
go——垃圾回收机制(GC)
golang源码分析:time/rate
浅议.NET遗留应用改造
PLC工作原理动画
LeetCode 622 设计循环队列[数组 队列] HERODING的LeetCode之路
How the sensor works
一款免费的容器安全 SaaS 平台使用记录
Bena's life cycle
什么是乙二醇二乙酸酯(EGDA)?
Likou Question of the Day - Day 46 - 344. Reverse Strings
Thread线程类基本使用(上)
How to use windbg check c # a thread stack size?
golang 源码分析:juju/ratelimit
【StoneDB性能相关工具】内存监控
OP analysis and design