根据语言规范lock(obj) statement;
将编译为:
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);
}
但是,它被编译为:
try
{
object lockObj = obj;
bool lockTaken = false;
Monitor.Enter(lockObj, ref lockTaken);
statement;
}
finally
{
if (lockTaken) Monitor.Exit(lockObj);
}
这似乎比必要的复杂得多。所以问题是,这种实施的优势是什么?