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) {
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.
source share