-1

I have been looking at some of the different ways people use mutexes to prevent multiple instances of their programs. One of the concerns with using a mutex in C# seems to be that your mutex can be disposed of by the garbage collector over time.

I'm using a mutex in my WPF project to enforce a single instance of the application as follows:

public partial class App : Application
{
    private string UniqueMutexName = string.Format("Global\\{{{0}}}", ((GuidAttribute)Assembly.GetEntryAssembly().GetCustomAttributes(typeof(GuidAttribute), false)[0]).Value);
    private static Mutex mutex = null;

    protected override void OnStartup(StartupEventArgs e)
    {
        bool singleInstance;
        mutex = new Mutex(true, UniqueMutexName, out singleInstance);

        if (!singleInstance)
        {
            NativeMethods.PostMessage((IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WindowsMessage.WM_INSTANCEATTEMPT, IntPtr.Zero, IntPtr.Zero);
            Current.Shutdown();
        }
        base.OnStartup(e);
    }
}

Does the fact that I declared the mutex as static prevent it from being disposed of by the garbage collector even though I have to instantiate it within the method, or do I need to do something else? I've seen everything from people wrapping the mutex in a using statement to using a try/finally block to manually dispose of the mutex, but since I'm using WPF and overriding the OnStartup method rather than editing the actual entry point, I can't really take that approach.

CJF
  • 147
  • 3
  • 15

1 Answers1

1

If an object become eligible for garbage collection because it was static and instantiated in a method, there would be a lot of crashing applications out there.

Another way to look at this, if you can access it (write code that can target that reference) and has not been set to null, then it will be ineligible

Does the fact that I declared the mutex as static prevent it from being disposed of by the garbage collector

The answer is yes (in any usual sense)


Additional Resources

Fundamentals of garbage collection

TheGeneral
  • 79,002
  • 9
  • 103
  • 141