What is the advantage of Monitor.Enter (object, ref bool) over Monitor.Enter (object)?

According to the language specification it lock(obj) statement;will be compiled as:

object lockObj = obj; // (the langspec doesn't mention this var, but it wouldn't be safe without it)
Monitor.Enter(lockObj);
try
{
    statement;
}
finally
{
    Monitor.Exit(lockObj);
}

However, it is compiled as:

try
{
    object lockObj = obj;
    bool lockTaken = false;
    Monitor.Enter(lockObj, ref lockTaken);
    statement;
}
finally
{
    if (lockTaken) Monitor.Exit(lockObj);
}

This seems a lot more complicated than necessary. So the question is, what is the advantage of this implementation?

+5
source share
2 answers

As always, Eric Lippert already answered this:

Incredible coding adventures: locks and exceptions don't mix

+5
source

"CLR #", . , finally , try - . undefined . , , , .

, , lock , - - .

+2

All Articles