0

I've looked around SO and the web for an answer but have only found one for other languages (c++, python) and reading hasn't quite provided a clear enough answer.

If a thread has a block of code that gets locked, and the thread dies for some reason (forcefully killed) while it is inside of the locked block, will the lock still be enforced (ie, other threads won't be able to use obtain that lock)?

Such as:

class myClass {
    private static object myLock = new Object();

    public void foobar()
    { 
        lock(myLock)
        {
            //code
        }
    }
}

If thread A dies and thread B attempts to call foobar, will it be able to? or will it deadlock?

sonic_7
  • 3
  • 4
  • "I've looked around SO and the web for an answer" - try to look up for "c# lock exception" in your favorite search engine. – Dennis Aug 02 '16 at 05:19
  • Edited. I don't believe this is a duplicate. I've removed the exception portion and am more interested in what happens if the thread itself dies while in the lock, without an exception. If the thread is killed, will the lock be released the same? – sonic_7 Aug 03 '16 at 00:04

2 Answers2

0

The lock statement is converted to try-finally with combination Monitor.Enter Monitor.Exit as shown below, and finally is executed in both cases when exception occurs or not which ensure the lock is released. This answer from Eric Lippert explains the lock implementation in c#.

System.Threading.Monitor.Enter(x);
try {
   ...
}
finally {
   System.Threading.Monitor.Exit(x);
}
Community
  • 1
  • 1
Adil
  • 146,340
  • 25
  • 209
  • 204
0

Statement

lock(myLock)
{
    //code
}

is equivalent to

System.Threading.Monitor.Enter(myLock);
try 
{ 
    //code
}
finally 
{ 
    System.Threading.Monitor.Exit(myLock); 
}

So if a thread dies, then exception would be thrown and finally statement would release the lock from the object myLock.

See documentation of Monitor class, it has good explanations and samples about locking concepts.

dotnetom
  • 24,551
  • 9
  • 51
  • 54