Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to Monitor.Enter without a matching Monitor.Exit?

If you have some blocks of code that you would like to prevent execution of when the object is being exited and cleaned up, could a lock be used to prevent the execution?

Monitor.TryEnter(cleanupLock, ref acquiredLock);

TryEnter could be used to ensure that the code is not executed, and since it does not wait for the lock there will not be a deadlock.

Another thread would grab the lock when it determines that it is time for shutdown.

Monitor.Enter(cleanupLock);

If the cleanup thread never calls

Monitor.Exit(cleanupLock);

would this cause a problem?

like image 977
Doug Ferguson Avatar asked Feb 22 '10 18:02

Doug Ferguson


1 Answers

Yes, not calling Monitor.Exit for a succesful Monitor.TryEnter or Monitor.Enter is a fast track to a deadlock in your application. You may be able to get it to work in a very limited scenario but eventually the code or scenario will change and this will come back to bite you. Just don't do it.

like image 105
JaredPar Avatar answered Sep 22 '22 18:09

JaredPar