What happens to Monitor.Enter without a matching Monitor.Exit?
.net, c#, multithreading
Solution
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.
Problem
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?