Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF mutex for single app instance not working

Tags:

I'm trying to use the mutex method for only allowing one instance of my app to run. That is - I only want a max of one instance for all users on a machine. I've read through the various other threads on this issue and the solution seems straightforward enough but in testing I can't get my second instance to not run. Here is my code...

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

        base.OnStartup(e);
    }
}
like image 871
flobadob Avatar asked Mar 21 '11 10:03

flobadob


1 Answers

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.

like image 170
Willem van Rumpt Avatar answered Sep 21 '22 15:09

Willem van Rumpt