views:

140

answers:

2

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.

+4  A: 

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.

Jon Skeet
Yup, lock has been changed to use the new construct (or at least it was in beta1)
Brian Rasmussen
I will accept the answer if you can answer to Eamon Nerbonne question ;)
Guillaume
A: 

You should not bother creating the monitor enter/exit code by hand, when you can use the lock statement:

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

The compiler takes care of doing the right expansion for you. Sweet sugar indeed.

Jordão
You can't always use the lock statement so we still have to know how to Enter/Exit a lock moreover when I use a keyword I want to know what happens behind. But you are right, when it's possible I prefer lock keyword.
Guillaume
For the example that you gave, you should really use `lock`. If you intend to enter and exit the monitor in separate methods, then yes, you should know how to write the code yourself.
Jordão