Ful*_*oof 0 c# multithreading synchronization locking
MSDN告诉我,使用锁相当于使用监视器,但更简洁,更不容易出错.
你能给我一个简单的(单个过程)例子为什么我会被迫使用,Monitor因为它无法完成lock?
你能给我一个简单的(单个过程)例子为什么当锁定不够时我会被迫使用监视器?
当然.假设你想采取行动,如果你能获得锁,但如果其他对象已经拥有它,你不想阻塞超过一定时间更长:
bool gotMonitor = false;
try
{
Monitor.TryEnter(monitor, 500, ref gotMonitor);
if (gotMonitor)
{
// Okay, we're in the lock. We can do something useful now.
}
else
{
// Timed out - do something else
}
}
finally
{
if (gotMonitor)
{
Monitor.Exit(monitor);
}
}
Run Code Online (Sandbox Code Playgroud)
(请注意,我故意不 使用TryEnter只返回成功/失败的重载 - 我使用的版本更可靠,因为ref参数的设置相对于锁定获取是原子的.)