I am reviewing some code and one of the code analysis (fxCop) warnings has gotten me very confused. The code implements a few mutex's by creating variables at the start of the class, similar to this:
private Mutex myMutex = new Mutex();
fxCop is popping up with a message saying that I must implement IDisposable for the class as the Mutex class implements it - this is warning CA1001. However looking at Mutex it has no dispose method.
Turns out that Mutex uses a SafeWaitHandle (which implements IDisposable - guessing this is what fxCop is picking up), but mutex doesn't actually dispose it via the standard disposable pattern. It has a private method which is assigned to a delegate using the RuntimeHelpers.CleanupCode, which as I understand it means it will be run on an exception.
This brings up two questions:
- Is Mutex implemented correctly? If there is no exception in the Mutex then the SafeWaitHandle will never be disposed.
- What should I call in my dispose to cleanup the mutex?