4

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

4

2 回答 2

7

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.

于 2013-04-18T07:05:09.470 回答
0

you can check if your proccess is already running:

Process[] pname = Process.GetProcessesByName("YourProccessName");
if (pname.Length == 0)
    Application.Exit();
于 2013-04-18T06:58:54.683 回答