Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid from running more than one instance

Tags:

c#

mutex

wpf

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

like image 580
Ofir Avatar asked Mar 24 '23 06:03

Ofir


1 Answers

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.

like image 93
Sergey Berezovskiy Avatar answered Mar 31 '23 14:03

Sergey Berezovskiy