I'm trying to set a mutex in order to allow running my application in one instance only. I wrote the next code (like suggested here in other 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
}
}
}
Regretfully this code isn't working. I can launch my application in multiple instances. Is anyone has an idea what is wrong in my code? Thanks
You are disposing Mutex just after running first instance of application. Store it in field instead and don't use 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);
}
}
Output parameter createdNew
returns false
if mutex already exist.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With