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?
The Lock statement is used in threading, that limit the number of threads that can perform some activity or execute a portion of code at a time. Exclusive locking in threading ensures that one thread does not enter a critical section while another thread is in the critical section of the code.
Avoid using 'lock keyword' on string object String object: Avoid using lock statements on string objects, because the interned strings are essentially global in nature and may be blocked by other threads without your knowledge, which can cause a deadlock.
According to Microsoft: The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.
CSharp Online Training Both Monitor and lock provides a mechanism that synchronizes access to objects. lock is the shortcut for Monitor. Enter with try and finally. Lock is a shortcut and it's the option for the basic usage.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With