Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can a lock statement exit without releasing the lock?

Tags:

c#

I have a strange problem, a deadlock problem, where if I pause the program using Visual Studio and inspect the threads I can only see two threads waiting on the lock. No thread appears to be inside the lock scope! Is Visual Studio just lying or how can a lock statement exit without releasing the lock?

Thanks

like image 985
CodingThunder Avatar asked Dec 17 '22 02:12

CodingThunder


2 Answers

This can happen under the following circumstances. Suppose you have

Enter();
try
{
   Foo();
}
finally
{
   Exit();
}

and a thread abort exception is thrown after the Enter but before the try. Now the monitor has been entered but the finally will never run because the exception was thrown before the try.

We've fixed this flaw in C# 4. In C# 4 the lock statement is now generated as

bool mustExit = false;
try
{
    Enter(ref mustExit);
    Foo();
}
finally
{
    if (mustExit) Exit();
}

Things can still go horribly wrong of course; aborting a thread is no guarantee that the thread ever aborts, that finally blocks ever run, and so on. You could end up in the unhandled exception event handler with the lock still taken. But this is at least a little better.

like image 192
Eric Lippert Avatar answered Jan 08 '23 20:01

Eric Lippert


This can happen if you manually call Monitor.Enter(something) without calling Monitor.Exit.

like image 36
SLaks Avatar answered Jan 08 '23 19:01

SLaks