Is the mutex implemented correctly and how can I dispose of it?

I'm going through the code and one of the code parsing warnings (fxCop) confused me a lot. The code implements multiple mutex by creating variables at the beginning of the class, similar to this:

private Mutex myMutex = new Mutex();

      

fxCop comes up with a message that I have to implement IDisposable for the class, as the Mutex class implements it - this is CA1001 warning , However, looking at Mutex, it doesn't have a dispose method.

It turns out that Mutex uses SafeWaitHandle (which implements IDisposable - guessing is what fxCop is typing), but mutex doesn In fact, this can be disposed of with the standard one-off template. It has a private method that is assigned to the delegate using RuntimeHelpers.CleanupCode which, as I understand it, means it will be run on an exception.

This begs two questions:

  • Is the Mutex function implemented correctly? If there is no exception in the Mutex, the SafeWaitHandle will never be removed.
  • What should I call at my disposal to clear the mutex?
+2


source to share


2 answers


Mutex

explicitly implements it IDisposable.Dispose

through its base class WaitHandle

. It exposes functionality Dispose

through a public method Close

(also inherited from WaitHandle

), which is a valid implementation of the hosting pattern, as recommended :

At times, a domain name is more appropriate than Dispose. For example, encapsulating a file may want to use the name Close method. In this case, you privately implement Dispose and create a public Close method that calls Dispose. (...) You can replace Close with the name of the method appropriate for your domain.



Several classes in System.IO

do this in the same way.

+5


source


using Close () still generates CA2000 in VS 2013 Pro Update 2. Dispose () is not available due to security level.

So, is there a bug or is it a bug in parsing the code from VS?



EDIT: Solved to use this code:

Mutex MyApplicationMutex = null;
try
{
  MyApplicationMutex = new Mutex(true, Program.g_ApplicationMutexName);
  if (MyApplicationMutex.WaitOne(0, false))
  {
    ...
  }
}
finally
{
  // Dispose Mutex
  if (MyApplicationMutex != null)
    MyApplicationMutex.Close();
 }

      

0


source







All Articles