Consider this code:
lock(myGuard)
{
// do some stuff that is being synchronized
}
the C# compiler generates the following code for you
Monitor.Enter(myGuard);
try
{
// do some stuff that is being synchronized
}
finally
{
Monitor.Exit(myGuard);
}
So lock is an exception proof (and short) way of acquiring a monitor and making sure it gets freed again.
but, if u use Monitor, the code blow is better.
if (!Monitor.TryEnter(obj, TimeSpan.FromSeconds(10))
{
throw new ApplicationException("Timeout waiting for lock");
}
try
{
... do something with shared state ...
}
finally
{
Monitor.Exit(obj);
}
A Mutex can be shared across processes, and is much more heavy-weight than a Monitor.
Use a Monitor unless you need to synchronize across process boundaries.
if u want to learn more, u can check

本文详细介绍了C#中锁机制的实现方式,并对比了使用lock关键字与Monitor类的区别。通过具体的代码示例展示了如何利用Monitor类实现超时等待机制,同时提到了Mutex与Monitor的不同应用场景。

2437

被折叠的 条评论
为什么被折叠?



