Avoid running multiple instances

I am trying to install a mutex to allow my application to run in only one instance. I wrote the following code (for example, suggested here in another post)

public partial class App : Application { private static string appGuid = "c0a76b5a-12ab-45c5-b9d9-d693faa6e7b9"; protected override void OnStartup(StartupEventArgs e) { using (Mutex mutex = new Mutex(false, "Global\\" + appGuid)) { if (!mutex.WaitOne(0, false)) { MessageBox.Show("Instance already running"); return; } base.OnStartup(e); //run application code } } } 

Unfortunately, this code does not work. I can run the application in multiple instances. Does anyone have an idea of ​​what's wrong with my code? Thanks

+4
source share
2 answers

You remove Mutex immediately after starting the first instance of the application. Store it in a field instead and do not use the using block:

 public partial class App : Application { private Mutex _mutex; private static string appGuid = "c0a76b5a-12ab-45c5-b9d9-d693faa6e7b9"; protected override void OnStartup(StartupEventArgs e) { bool createdNew; // thread should own mutex, so pass true _mutex = new Mutex(true, "Global\\" + appGuid, out createdNew); if (!createdNew) { _mutex = null; MessageBox.Show("Instance already running"); Application.Current.Shutdown(); // close application! return; } base.OnStartup(e); //run application code } protected override void OnExit(ExitEventArgs e) { if(_mutex != null) _mutex.ReleaseMutex(); base.OnExit(e); } } 

The createdNew output parameter returns false if the mutex already exists.

+7
source

you can check if your process is running:

 Process[] pname = Process.GetProcessesByName("YourProccessName"); if (pname.Length == 0) Application.Exit(); 
0
source

All Articles