我最近读了this post from Eric Lippert regarding the lock implementation in c#仍然存在一些问题。
在 4.0 实现中,如果在执行 finally block 中的 Monitor.Exit(temp) 之前发生线程中止或任何跨线程异常 - 是否会保持对对象的锁定?
是否有可能在此级别发生异常,使对象仍处于锁定状态?
最佳答案
In 4.0 implementation if a thread abort or any cross thread exception occurs just before the
Monitor.Exit(temp)
in the finally block is executed - would that keep the lock on the object?
让我们看一下该代码,以便其他读者清楚:
bool lockWasTaken = false;
var temp = obj;
try
{
Monitor.Enter(temp, ref lockWasTaken);
{
body
}
}
finally
{
if (lockWasTaken)
{
// What if a thread abort happens right here?
Monitor.Exit(temp);
}
}
您的问题无法回答,因为它基于一个错误的假设,即线程中止可能发生在 finally block 的中间。
线程中止不能发生在 finally block 的中间。这只是您永远不应该尝试中止线程的众多原因之一。整个线程可以在 finally block 中运行,因此是不可中止的。
Is there any possibility for an exception to occur at this level, leaving the object still in a locked state?
没有。线程中止将被延迟,直到控制离开 finally。解锁有效锁不会分配内存或引发其他异常。
关于c# - Lock 语句 - 它总是释放锁吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19225876/