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?
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.
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