Lock operator - does it always lock the lock?

I recently read this post from Eric Lippert regarding the implementation of locking in C # and there are still some questions.

In implementation 4.0, if a thread interruption or any cross-thread exception occurs immediately before Monitor.Exit (temp) is executed in the finally block, will it block the object?

Is there any chance of an exception occurring at this level, leaving the object in a locked state?

+6
source share
2 answers

In implementation 4.0, if a thread interruption or any cross-thread exception occurs just before Monitor.Exit(temp) in the finally block is executed, will the object lock still?

Let's look at this code so that it can be understood by 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 does not answer because it is based on a false assumption, namely that thread interruptions may occur in the middle of a finally block.

Interrupt attributes cannot occur in the middle of a finally block. This is one of the reasons you should not try to interrupt the thread. The entire thread can run in the finally block and therefore be non-abortive.

Is there any chance of an exception occurring at this level, leaving the object in a locked state?

No. Cancellation of the stream will be delayed until the control disappears completely. Unlocking a valid lock does not allocate memory or throw another exception.

+14
source

Read ThreadAbortException :

When this exception occurs, the runtime executes all finally blocks until the thread ends.

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

So yes, the castle will still be released. Whether this is desirable or not, this is a completely different matter โ€” you donโ€™t know that the thread is about to exit the lock โ€” it can be anywhere and may be in the middle of a mutation in the state that protected the lock โ€” as always, we advise you to avoid Thread.Abort .

+9
source

Source: https://habr.com/ru/post/955407/


All Articles