当前位置:网站首页>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
}
边栏推荐
猜你喜欢
ShardingSphere-proxy +PostgreSQL implements read-write separation (static strategy)
接口测试常用工具及测试方法(入门篇)
特拉维夫大学 | Efficient Long-Text Understanding with Short-Text Models(使用短文本模型进行高效的长文本理解)
Thread线程类基本使用(上)
Day35 LeetCode
ssdp协议搜索GB28181设备
用了TCP协议,就一定不会丢包吗?
Implement fashion_minst clothing image classification
广东省数字经济发展指引 1.0之建成数据安全保障体系
Day35 LeetCode
随机推荐
ECCV 2022 | 通往数据高效的Transformer目标检测器
56.【全局变量和局部变量专题】
Li Mu hands-on learning deep learning V2-bert and code implementation
Linphone 被叫方如何解析来电SIP消息中的自定义头消息
Axure9的元件用法
The software testing process specification is what?Specific what to do?
PLC工作原理动画
特拉维夫大学 | Efficient Long-Text Understanding with Short-Text Models(使用短文本模型进行高效的长文本理解)
ALV report learning summary
"A daily practice, happy water problem" 1374. Generate a string with an odd number of each character
什么是乙二醇二乙酸酯(EGDA)?
Informatics Olympiad All-in-One (1260: [Example 9.4] Intercepting Missiles (Noip1999))
pytorch的tensor创建和操作记录
如何使用windbg查看C#某个线程的栈大小 ?
DataGrip 安装教程 详细版
Implement fashion_minst clothing image classification
软件成分分析:华为云重磅发布开源软件治理服务
PyTorch分布式backends
「 每日一练,快乐水题 」1374. 生成每种字符都是奇数个的字符串
一款免费的容器安全 SaaS 平台使用记录