Arian Kulp's Blog
opinion, insight, and occasional code

Mutexes and garbage collection

Monday, February 13, 2006 10:37 PM

Michael H. sent me a comment yesterday stating that my "Tricking Out Your Applications" code had a bad flaw. Recall that I show the use of a System.Threading.Mutex object in the Main method in order to prevent more than one instance of the application from running. Michael noticed that, while this works in Debug mode, it does not work in Release mode. Weird, I thought. I tried it myself, it worked fine, and I let him know there must be something else at fault (like any American, my first instinct is self-preservation -- it's not my fault, you must have done something wrong!).

Michael didn't stop there. He did some research and found this great link:    http://weblogs.asp.net/savanness/archive/2003/05/23/7496.aspx

He's absolutely right! The gist of the problem is that the deterministic garbage collector notices that the Mutex object isn't used again after the initial creation of the object. Therefore it sweeps away that reference, thus causing the ownership to disappear. A second instance gets the lock with no conflict.

But wait! Why didn't this happen to me then (perhaps you are wondering)? As it turns out, in Debug mode, garbage collection works a bit differently. References don't get cleaned up until they go out of scope -- basically the determinism goes away. This makes it safe to examine the state of a variable declared earlier in a method, even if it is no longer used. In Release mode, though, as soon as it's done being used (as the gc thinks anyway), it's gone.

The simple solution (as in the above link, and tested by me), is to put the creation to the Mutex in a using block. This creates an implicit call to Dispose at the end of the block. You could also add a call to ReleaseMutex at the end of the method.

Because of the way garbage collection works, you wouldn't see this happen (most of the time) if you started up two instance in rapid succession (even in Release mode).

Thanks Michael for pointing this out, and for doing the Googling that I should have done!




Feedback

# re: Mutexes and garbage collection

Does the code at Coding4Fun reflect this change? 4/9/2006 3:13 AM | Daniel

# re: Mutexes and garbage collection

Nope. Getting that code updated is a bigger deal than it should be for me! Sorry if that complicates things. 4/9/2006 11:19 AM | Arian



Comments have been closed on this topic.