似乎这些代码片段的行为应该相同:
1:Monitor.TryEnter(对象)
if (Monitor.TryEnter(lockObject))
{
try
{
DoSomething();
}
finally
{
Monitor.Exit(lockObject);
}
}
2:Monitor.TryEnter(object, ref bool) - .NET 4.0 中引入
bool lockAcquired;
try
{
Monitor.TryEnter(lockObject, ref lockAcquired);
if (lockAcquired)
{
DoSomething();
}
}
finally
{
if (lockAcquired)
{
Monitor.Exit(lockObject);
}
}
我从 the overload taking a
ref bool
parameter 上的 MSDN 文档中看到:If the lock was not taken because an exception was thrown, the variable specified for the lockTaken parameter is false after this method ends. This allows the program to determine, in all cases, whether it is necessary to release the lock.
但文档还指出,过载仅采用
object
除了 ArgumentNullException
之外,参数不会抛出任何异常.所以看起来如果在代码片段 中抛出异常1 以上,只能是因为lockObject
是 null
,在这种情况下,没有锁定(并且 TryEnter
会返回 false
),所以 Monitor.Exit
不需要调用。显然,他们不会无缘无故地引入这种重载。那么
Monitor.TryEnter(object, ref bool)
是什么场景方法意在解决?
最佳答案
见:Locks and exceptions do not mix
关于.net - Monitor.TryEnter(object) 和 Monitor.TryEnter(object, ref bool) 之间存在什么重要区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3674650/