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
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.
This can happen if you manually call Monitor.Enter(something)
without calling Monitor.Exit
.
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