WPF mutex for single app instance not working WPF mutex for single app instance not working wpf wpf

WPF mutex for single app instance not working


You're also disposing the mutex in the same method, so the mutex only lives for the duration of the method. Store the mutex in a static field, and keep it alive for the duration of your application.


Here is my new code which has the answer provided by @Willem van Rumpt (and @OJ)...

public partial class App : Application{    private Mutex _instanceMutex = null;    protected override void OnStartup(StartupEventArgs e)    {        // check that there is only one instance of the control panel running...        bool createdNew;        _instanceMutex = new Mutex(true, @"Global\ControlPanel", out createdNew);        if (!createdNew)        {            _instanceMutex = null;            Application.Current.Shutdown();            return;        }        base.OnStartup(e);    }    protected override void OnExit(ExitEventArgs e)    {                  if(_instanceMutex != null)            _instanceMutex.ReleaseMutex();        base.OnExit(e);    }}


You're destroying the Mutex immediately after you've created it and tested it. You need to keep the Mutex reference alive for lifetime of your application.

Make the Mutex a member/field of your Application class.Release the mutex when your application shuts down.