简体   繁体   English

避免运行多个实例

[英]Avoid from running more than one instance

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. 在运行第一个应用程序实例后,您正在处置Mutex Store it in field instead and don't use using block: 将其存储在字段中,不要使用using块:

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. 如果互斥锁已存在,则输出参数createdNew将返回false

you can check if your proccess is already running: 你可以检查你的进程是否已经运行:

Process[] pname = Process.GetProcessesByName("YourProccessName");
if (pname.Length == 0)
    Application.Exit();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM