看来,这些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布尔参数:
![C Monitor.TryEnter 抛出异常 System.Threading.SynchronizationLockException](https://p.xsw88.cn/allimgs/daicuo/20230903/2647.png)
如果没有采取锁,因为一个 异常被抛出,变量 为的 lockTaken 的参数指定 是的错误后,这个方法结束。本 允许程序确定,在 所有的情况下,是否有必要对 解除锁定。
但文档的也的规定,超载只服用了对象
参数没有抛出异常比 ArgumentNullException 。因此,它好像如果一个异常被抛出code段 1 以上,这只能是因为
lockObject
是空
,在这种情况下,没有锁被采取(与 TryEnter
将又回到假
)反正,所以 Monitor.Exit
通话就没有必要。
显然,他们就不用介绍了此重载无缘无故。那么,什么情况下是 Monitor.TryEnter(对象,参考布尔)
方法旨在解决?
请参阅: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?
See: Locks and exceptions do not mix
相关推荐
最新文章