views:

209

answers:

4

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?

+7  A: 

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.

JaredPar
Going against conventional usage is a good argument against this pattern.
Doug Ferguson
+5  A: 

The only "problem" will be that no other code will ever be able to aquire a lock on the cleanupLock variable.

This may or may not be a problem - however, it's kind of an abuse of Monitor, so I would avoid doing this. It would be better to handle this situation in a more common manner, IMO.

Reed Copsey
A: 

would this cause a problem?

Yes. The lock would never be released.

Source:

The calling thread must own the lock on the obj parameter. If the calling thread owns the lock on the specified object, and has made an equal number of Exit and Enter calls for the object, then the lock is released. If the calling thread has not invoked Exit as many times as Enter, the lock is not released.

Randolpho
+1  A: 

If this is a cleanup shutdown sequence then its a more or less OK. You run the risk of someone checking in somewhere, by mistacke, a wait-for-acquire of cleanupLock. It can slip into code unnoticed, and show up at the most embaracing moment. The result would be a thread that refuses to shut down, maybe keeping the process alive ad-nauseam. But, at the end of the day, you run the very same risk with any other method you would use (eg. global shutdown flag).

Remus Rusanu