简体   繁体   中英

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.

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?

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?

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.

Thread aborts cannot happen in the middle of a finally block. 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.

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 :

When this exception is raised, the runtime executes all the finally blocks before ending the thread

(This includes any finally block that is currently executing when Thread.Abort is called)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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