简体   繁体   English

锁定语句 - 是否始终释放锁定?

[英]Lock statement - does it always release the lock?

I have recently read this post from Eric Lippert regarding the lock implementation in c# and still some questions remain. 我最近阅读了Eric Lippert关于c#中锁实现的这篇文章 ,但仍然存在一些问题。

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? 在4.0实现中,如果在执行finally块中的Monitor.Exit(temp)之前发生了线程中止或任何跨线程异常 - 是否会保持对对象的锁定?

Is there any possibility for an exception to occur at this level, leaving the object still in a locked state? 是否有可能在此级别发生异常,使对象仍处于锁定状态?

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? 在4.0实现中,如果在执行finally块中的Monitor.Exit(temp)之前发生了线程中止或任何跨线程异常 - 是否会保持对对象的锁定?

Let's take a look at that code, so that it is clear to other readers: 让我们来看看那段代码,以便其他读者清楚:

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); 
  }
}

Your question is not answerable because it is based on a false assumption, namely, that thread aborts can happen in the middle of a finally block. 你的问题是不可回答的,因为它是基于一个错误的假设,即线程中止可能发生在finally块的中间。

Thread aborts cannot happen in the middle of a finally block. 线程中止不会发生在finally块的中间。 That is just one reason amongst many reason why you should never attempt to abort a thread. 这只是为什么你永远不应该试图中止一个线程的原因之一。 The entire thread could be running in a finally block, and therefore be not-abortable. 整个线程可以在finally块中运行,因此不可中止。

Is there any possibility for an exception to occur at this level, leaving the object still in a locked state? 是否有可能在此级别发生异常,使对象仍处于锁定状态?

No. A thread abort will be delayed until control leaves the finally. 不会。线程中止将被延迟,直到控制离开最终。 Unlocking a valid lock does not allocate memory or throw another exception. 解锁有效锁不会分配内存或抛出另一个异常。

Read up about ThreadAbortException : 阅读ThreadAbortException

When this exception is raised, the runtime executes all the finally blocks before ending the thread 引发此异常时,运行时会在结束线程之前执行所有finally

(This includes any finally block that is currently executing when Thread.Abort is called) (这包括调用Thread.Abort当前正在执行的任何finally块)

So yes, the lock will be released still. 所以是的,锁定将被释放。 Whether this is desirable or not is a very different matter though - you don't know that the thread is just about to release the lock - it could be anywhere, and may be in the middle of mutating the state that the lock was protecting - so as always, the advice is to avoid Thread.Abort . 这是否可取是一个非常不同的问题 - 你不知道线程即将释放锁 - 它可能在任何地方,并且可能正在改变锁保护的状态 - 一如既往,建议是避免Thread.Abort

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM