-1

I've got some code inside of a lock(SyncRoot) { ... }, if the thread crashes inside of the lock(){} statement, will the lock be held forever or is it automatically realeased when the thread "leaves" the block, even if its by an unhandled exception?

taracus
  • 393
  • 1
  • 5
  • 19

1 Answers1

1

lock(obj) { ... } is just a syntactic sugar for

Monitor.Enter(obj);
try
{ ... }
finally
{
    Monitor.Exit(obj);
}

and in C# 4.0 it was changed to

bool acquaired = false;
try
{
    Monitor.Enter(obj, ref acquired);
    ...
}
finally
{
    if (acquired)
    {
        Monitor.Exit(obj)
    }
}

Now, prior to .Net 4.0, it was possible that ThreadAbortException would be thrown between the Monitor.Enter(obj); and the beginning of the try block - and that would've created a dead lock (which means, no thread can access the lock, and they would remain blocked). Now even this is impossible. Anyway, event if an exception was thrown inside the lock, the lock would be released because of the finally block.

** I believe @Jon Skeet deserve credit for this.

Shlomi Borovitz
  • 1,700
  • 9
  • 9
  • 1
    Thank you for the quick answer, StackOverFlow taught me more programming than my Masters Degreen in Computer Science... – taracus Mar 09 '14 at 13:55
  • Take note that I don't see a `Monitor.Release` method.. I'm contacting Jon Skeet, but it might be a mistake ( then it is probably `Monitor.Exit` ) – Shlomi Borovitz Mar 09 '14 at 14:00