MSDN tells me that using lock is equivalent to using monitor but is more concise and less error prone .
Can you give me a simple (single process) example why would I be forced to use Monitor
because it cannot be done with lock
?
Can you give me a simple (single process) example why would I be forced to use monitor when the lock is not enough?
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.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.