msdn文章Thread Synchronization (C# Programming Guide)指定:
lock (x)
{
DoSomething();
}
相当于:
System.Object obj = (System.Object)x;
System.Threading.Monitor.Enter(obj);
try
{
DoSomething();
}
finally
{
System.Threading.Monitor.Exit(obj);
}
然后是:
"Using the lock keyword is generally preferred over using the Monitor class directly, ... because lock insures that the underlying monitor is released, even if the protected code throws an exception"
这句话是否意味着最后一个使用监视器的代码片段不能确保“释放底层监视器,即使 protected 代码抛出异常”?
为什么?
好吧,我对相互矛盾的断言感到困惑“等效”和不(一种用法确保而另一种用法,等效,不)关于相同。
最佳答案
粗体文本所指的情况更像是这样:
Monitor.Enter(obj);
DoSomethingThatThrows();
Monitor.Exit(obj);
如果没有 try-finally,抛出异常将绕过 Monitor.Exit
调用。
关于c# - 为什么锁确保底层监视器被释放而直接使用监视器却没有?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15020064/