.Net4,Monitor.Enter(lockObject,acquiredLock) [英] .Net4, Monitor.Enter(lockObject, acquiredLock)

查看:50
本文介绍了.Net4,Monitor.Enter(lockObject,acquiredLock)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In .Net4, Monitor.Enter(Object) is marked as obsolete :

[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)与此用法:

And there is a new method Monitor.Enter(lockObject, acquiredLock) with this usage :

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之前的最后一个异步异常发生了怎么办?

Is it wrong ? Why ? Maybe with an interupt after the enter but before the try ?
As Eamon Nerbonne asked : what happens if there's an async exception in the finally right before monitor.exit?

答案: ThreadAbortException

引发此异常时, 运行时执行所有的finally 在结束线程之前阻塞.

When this exception is raised, the runtime executes all the finally blocks before ending the thread.

推荐答案

正如您在问题末尾所建议的那样,问题是

As you suggest right at the end of the question, the problem is that an asynchronous exception could be thrown after the call to Monitor.Enter but before you enter the try block.

新的处理方式确保无论发生什么情况,您都将敲击finally块,并能够释放获得 if 的锁. (例如,如果Monitor.Enter引发异常,则可能无法获取它.)

The new way of doing things makes sure that whatever happens, you'll hit the finally block and be able to release the lock if you acquired it. (You may not acquire it if Monitor.Enter throws an exception, for example.)

IIRC,这是在定位.NET 4.0时lock关键字的新行为.

IIRC, this is the new behaviour of the lock keyword when targeting .NET 4.0.

这篇关于.Net4,Monitor.Enter(lockObject,acquiredLock)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆