According to the language specification lock(obj) statement; would 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);
}
That seems to be a lot more complicated than necessary. So the question is, what’s the advantage of that implementation?
As always, Eric Lippert has already answered this:
Fabulous Adventures In Coding: Locks and exceptions do not mix
Excerpt: