C#互斥锁问题以阻止第二个实例
本文关键字:第二个 实例 问题 | 更新日期: 2023-09-27 17:59:42
我遇到了一个有趣的问题(C#/WPF应用程序)。我使用此代码是为了防止应用程序的第二个实例运行。
Mutex _mutex;
string mutexName = "Global''{SOME_GUID}";
try
{
_mutex = new Mutex(false, mutexName);
}
catch (Exception)
{
//Possible second instance, do something here.
}
if (_mutex.WaitOne(0, false))
{
base.OnStartup(e);
}
else
{
//Do something here to close the second instance
}
如果我把代码直接放在OnStartup方法下的主exe中,它就可以工作了。然而,如果我包装相同的代码并将其放在一个单独的程序集.dll中,并从OnStartup方法调用函数,它就不会检测到第二个实例。
有什么建议吗?
什么是_mutex变量生存时间,当它被放在Dll中时?也许它在OnStartup退出后被销毁了。将Single Instance包装器类保留为应用程序类成员,以具有与原始_mutex变量相同的生存时间。
static bool IsFirstInstance()
{
// First attempt to open existing mutex, using static method: Mutex.OpenExisting
// It would fail and raise an exception, if mutex cannot be opened (since it didn't exist)
// And we'd know this is FIRST instance of application, would thus return 'true'
try
{
SingleInstanceMutex = Mutex.OpenExisting("SingleInstanceApp");
}
catch (WaitHandleCannotBeOpenedException)
{
// Success! This is the first instance
// Initial owner doesn't really matter in this case...
SingleInstanceMutex = new Mutex(false, "SingleInstanceApp");
return true;
}
// No exception? That means mutex ALREADY existed!
return false;
}