[英]Avoid from running more than one instance
我正在嘗試設置一個互斥鎖,以便只允許在一個實例中運行我的應用程序。 我寫了下一個代碼(如其他帖子中的建議)
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
塊:
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
。
你可以檢查你的進程是否已經運行:
Process[] pname = Process.GetProcessesByName("YourProccessName");
if (pname.Length == 0)
Application.Exit();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.