.Net4,Monitor.Enter(lockObject,acquiredLock)

时间:2009-10-23 09:28:20

标签: .net locking thread-safety

在.Net4中,Monitor.Enter(Object)被标记为已过时:

[ObsoleteAttribute("This method does not allow its caller to reliably release the lock.  Please use an overload with a lockTaken argument instead.")]
public static void Enter(
    Object obj
)

这种用法有一种新的方法Monitor.Enter(lockObject, acquiredLock)

bool acquiredLock = false;

try
{
    Monitor.Enter(lockObject, ref acquiredLock);

    // Code that accesses resources that are protected by the lock.

}
finally
{
    if (acquiredLock)
    {
        Monitor.Exit(lockObject);
    }
}

我曾经这样做过:

Monitor.Enter(lockObject);
try
{

    // Code that accesses resources that are protected by the lock.
}
finally
{
    Monitor.Exit(lockObject);
}

是不是错了?为什么? 也许在进入之后但在尝试之前进行了中断?
正如Eamon Nerbonne所说:如果在monitor.exit之前的最后一个异步异常中会发生什么?

答案:ThreadAbortException

  

当引发此异常时,   运行时最终执行所有   在结束线程之前阻塞。

1 个答案:

答案 0 :(得分:5)

正如您在问题末尾所建议的那样,问题是在调用Monitor.Enter之后但在您输入try阻止之前,可能会抛出asynchronous exception

新的做事方式确保无论发生什么,你都会点击finally块并且能够释放锁如果你获得了它。 (例如,如果Monitor.Enter抛出异常,则可能无法获取它。)

IIRC,这是针对.NET 4.0时lock关键字的新行为。