[英]Can you give me a simple example when I am to use “monitor” because it cannot be done with “lock”?
MSDN tells me that using lock is equivalent to using monitor but is more concise and less error prone . MSDN告诉我,使用锁等效于使用监视器, 但更简洁,更不易出错 。
Can you give me a simple (single process) example why would I be forced to use Monitor
because it cannot be done with lock
? 您能给我一个简单的(单个过程)示例,为什么由于无法使用
lock
来强制我使用Monitor
?
Can you give me a simple (single process) example why would I be forced to use monitor when the lock is not enough?
您能给我一个简单的(单个过程)示例,为什么在锁不够时为什么会强制使用Monitor?
Sure. 当然。 Suppose you want to take an action if you can acquire the lock, but if some other object already owns it, you don't want to block for longer than a certain time:
假设您想采取行动, 如果可以获取该锁,但是如果某个其他对象已经拥有该锁,则您不想阻塞的时间超过一定时间:
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);
}
}
(Note that I'm deliberately not using the overload of TryEnter
which just returns success/failure - the version I'm using is more reliable, as the setting of the ref
parameter is atomic with respect to the lock acquisition.) (请注意,我故意不 使用
TryEnter
的重载,后者仅返回成功/失败 -我使用的版本更可靠,因为ref
参数的设置相对于锁获取而言是原子的。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.