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.