我正在尝试使用互斥方法只允许我的应用程序的一个实例运行.也就是说 - 我只想为一台机器上的所有用户提供最多一个实例.我已经阅读了关于这个问题的各种其他线程,解决方案看起来很简单,但在测试中我不能让我的第二个实例不能运行.这是我的代码......
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
// check that there is only one instance of the control panel running...
bool createdNew = true;
using (Mutex instanceMutex = new Mutex(true, @"Global\ControlPanel", out createdNew))
{
if (!createdNew)
{
Application.Current.Shutdown();
return;
}
}
base.OnStartup(e);
}
}
Run Code Online (Sandbox Code Playgroud)
Wil*_*mpt 35
您也使用相同的方法处理互斥锁,因此互斥锁仅在方法持续时间内存在.将互斥锁存储在静态字段中,并在应用期间保持活动状态.
flo*_*dob 28
这是我的新代码,其答案由@Willem van Rumpt(和@OJ)提供......
public partial class App : Application
{
private Mutex _instanceMutex = null;
protected override void OnStartup(StartupEventArgs e)
{
// check that there is only one instance of the control panel running...
bool createdNew;
_instanceMutex = new Mutex(true, @"Global\ControlPanel", out createdNew);
if (!createdNew)
{
_instanceMutex = null;
Application.Current.Shutdown();
return;
}
base.OnStartup(e);
}
protected override void OnExit(ExitEventArgs e)
{
if(_instanceMutex != null)
_instanceMutex.ReleaseMutex();
base.OnExit(e);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14139 次 |
| 最近记录: |