与Monitor.Enter(对象)相比,Monitor.Enter(object,ref bool)的优势是什么?

Wor*_*mbo 5 c# concurrency c#-3.0 c#-4.0

根据语言规范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);
}
Run Code Online (Sandbox Code Playgroud)

但是,编译为:

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

这似乎比必要的要复杂得多.所以问题是,该实施的优势是什么?

Nic*_*ler 5

一如既往,Eric Lippert已经回答了这个问题:

编码中的精彩冒险:锁和异常不会混合

  • 该链接现已失效。截至今天,可以在这里找到这篇文章:https://ericlippert.com/2009/03/06/locks-and-exceptions-do-not-mix/ (2认同)