1. WPF单实例启动的核心需求解析
在桌面应用开发中,单实例(Single Instance)是一个经典需求场景。想象这样一个场景:用户双击了三次应用图标,结果系统里同时运行着三个相同的程序副本——这不仅浪费系统资源,更可能导致数据冲突。我在实际项目中就遇到过用户误操作导致多个实例同时修改同一份配置文件,最终数据损坏的情况。
WPF作为.NET生态中最主流的桌面UI框架,原生并未提供单实例机制。但通过Windows底层的进程间通信(IPC)技术,我们可以实现这样的控制逻辑。核心原理是:当程序启动时,先检查是否已有实例在运行。如果有,则激活已有窗口并传递参数;如果没有,才正常启动新实例。
这种机制特别适合以下场景:
- 需要严格控制资源占用的应用(如工业控制软件)
- 需要维护单一数据源的应用(如配置管理工具)
- 需要避免重复操作的应用(如邮件客户端)
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 基于Mutex的系统级单实例实现
2.1 Mutex的工作原理
Mutex(互斥锁)是操作系统提供的同步原语,它的特殊之处在于可以跨进程工作。当我们在WPF应用中使用如下代码创建具名Mutex时:
csharp复制bool createdNew;
_mutex = new Mutex(true, "MyAppSingleInstanceMutex", out createdNew);
系统会在内核层面维护这个锁。createdNew参数是关键:如果返回true,表示当前进程成功创建了Mutex(即没有其他实例在运行);如果返回false,则表示Mutex已存在(已有实例运行)。
2.2 完整实现方案
在App.xaml.cs中,我们可以这样实现:
csharp复制public partial class App : Application
{
private const string MutexName = "MyCompany.MyApp.SingleInstanceMutex";
private static Mutex _mutex;
protected override void OnStartup(StartupEventArgs e)
{
bool createdNew;
_mutex = new Mutex(true, MutexName, out createdNew);
if (!createdNew)
{
// 激活已有实例
ActivateExistingInstance();
Shutdown();
return;
}
base.OnStartup(e);
}
private void ActivateExistingInstance()
{
// 通过Windows API找到并激活已有窗口
var currentProcess = Process.GetCurrentProcess();
foreach (var process in Process.GetProcessesByName(currentProcess.ProcessName))
{
if (process.Id == currentProcess.Id) continue;
NativeMethods.SetForegroundWindow(process.MainWindowHandle);
NativeMethods.ShowWindow(process.MainWindowHandle, NativeMethods.SW_RESTORE);
break;
}
}
protected override void OnExit(ExitEventArgs e)
{
_mutex?.ReleaseMutex();
_mutex?.Dispose();
base.OnExit(e);
}
}
internal static class NativeMethods
{
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
public const int SW_RESTORE = 9;
}
