Monitor.TryEnter(对象)和Monitor.TryEnter(对象,参考布尔)之间有什么重要的差异存在? [英] What important difference exists between Monitor.TryEnter(object) And Monitor.TryEnter(object, ref bool)?
问题描述
看来,这些code段应该表现相同:
1:Monitor.TryEnter(对象)
如果(Monitor.TryEnter(lockObject))
{
尝试
{
做一点事();
}
最后
{
Monitor.Exit(lockObject);
}
}
2:Monitor.TryEnter(对象,参考布尔) - 介绍了.NET 4.0
布尔lockAcquired;
尝试
{
Monitor.TryEnter(lockObject,楼盘lockAcquired);
如果(lockAcquired)
{
做一点事();
}
}
最后
{
如果(lockAcquired)
{
Monitor.Exit(lockObject);
}
}
我从超载采取 REF布尔
参数:
如果没有采取锁,因为一个 异常被抛出,变量 为的 lockTaken 的参数指定 是的错误后,这个方法结束。本 允许程序确定,在 所有的情况下,是否有必要对 解除锁定。
但文档的也的规定,超载只服用了对象
参数没有抛出异常比 ArgumentNullException 其他code>。因此,它好像如果一个异常被抛出code段 1 以上,这只能是因为
lockObject
是空
,在这种情况下,没有锁被采取(与 TryEnter
将又回到假
)反正,所以 Monitor.Exit
通话就没有必要。
显然,他们就不用介绍了此重载无缘无故。那么,什么情况下是 Monitor.TryEnter(对象,参考布尔)
方法旨在解决?
- Monitor.TryEnter可以成功,那么asynchroneous例外,像ThreadAbortException或OutOfMemoryException异常(即不可见的分配可能发生)被触发。那么锁将采取但从未发布。
请参阅:<一href="http://blogs.msdn.com/b/ericlippert/archive/2009/03/06/locks-and-exceptions-do-not-mix.aspx">Locks和异常不混合
It seems that these code snippets ought to behave identically:
1: Monitor.TryEnter(object)
if (Monitor.TryEnter(lockObject))
{
try
{
DoSomething();
}
finally
{
Monitor.Exit(lockObject);
}
}
2: Monitor.TryEnter(object, ref bool) - introduced in .NET 4.0
bool lockAcquired;
try
{
Monitor.TryEnter(lockObject, ref lockAcquired);
if (lockAcquired)
{
DoSomething();
}
}
finally
{
if (lockAcquired)
{
Monitor.Exit(lockObject);
}
}
I see from the MSDN documentation on the overload taking a ref bool
parameter:
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.
But the documentation also states that the overload taking only the object
parameter throws no exceptions other than ArgumentNullException
. So it seems like if an exception were thrown in code snippet 1 above, it could only be because lockObject
is null
, in which case no lock was taken (and TryEnter
would've returned false
) anyway, so the Monitor.Exit
call would not be needed.
Clearly they would not have introduced this overload for no reason. So what scenario is the Monitor.TryEnter(object, ref bool)
method intended to address?
- Monitor.TryEnter could succeed and then an asynchroneous exception like ThreadAbortException or OutOfMemoryException (that can happen without visible allocations) is triggered. Then the lock would be taken but never released.
See: Locks and exceptions do not mix
这篇关于Monitor.TryEnter(对象)和Monitor.TryEnter(对象,参考布尔)之间有什么重要的差异存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!