避免运行多个实例

Ofi*_*fir 4 c# wpf mutex

我正在尝试设置一个互斥锁,以便只允许在一个实例中运行我的应用程序.我写了下一个代码(如其他帖子中的建议)

 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
            }
        }

    }
Run Code Online (Sandbox Code Playgroud)

遗憾的是这段代码不起作用.我可以在多个实例中启动我的应用程序.有人知道我的代码有什么问题吗?谢谢

Ser*_*kiy 7

在运行第一个应用程序实例后,您正在处置Mutex.将其存储在字段中,不要使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果互斥锁已存在,则createdNew返回输出参数false.