views:

254

answers:

1

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:

  1. Is Mutex implemented correctly? If there is no exception in the Mutex then the SafeWaitHandle will never be disposed.
  2. What should I call in my dispose to cleanup the mutex?
+4  A: 

Mutex explicitly implements IDisposable.Dispose through its base class WaitHandle. It exposes the Dispose functionality through its public Close method (also inherited from WaitHandle), which is a valid implementation of the dispose pattern, according to the guidelines:

Occasionally a domain-specific name is more appropriate than Dispose. For example, a file encapsulation might want to use the method name Close. In this case, implement Dispose privately and create a public Close method that calls Dispose. (...) You can replace Close with a method name appropriate to your domain.

Several classes in System.IO do it this way as well.

Joren
doh, of course it does :) The moment I saw that the gears turned and it made sense.
Robert MacLean