.Net4, Monitor.Enter(lockObject, acquiredLock)
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 (acquire开发者_开发知识库dLock)
{
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.
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.
精彩评论