.Net4, Monitor.Enter(lockObject, acquiredLock)

喜你入骨 提交于 2019-12-12 16:25:29

问题


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
)

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);
    }
}

I used to do it this way :

Monitor.Enter(lockObject);
try
{

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

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?

Answer : ThreadAbortException

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


回答1:


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.

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, this is the new behaviour of the lock keyword when targeting .NET 4.0.



来源:https://stackoverflow.com/questions/1612325/net4-monitor-enterlockobject-acquiredlock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!