gpt4 book ai didi

c# - 避免运行多个实例

转载 作者:太空狗 更新时间:2023-10-30 00:42:21 25 4
gpt4 key购买 nike

我正在尝试设置一个互斥锁,以便仅在一个实例中运行我的应用程序。我写了下一个代码(就像在其他帖子中建议的那样)

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

}

很遗憾,此代码无法正常工作。我可以在多个实例中启动我的应用程序。有谁知道我的代码有什么问题吗?谢谢

最佳答案

您正在处理 Mutex在运行第一个应用程序实例之后。将其存储在字段中,不要使用 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);
}
}

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

关于c# - 避免运行多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16076400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com