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.