static class Program 里的全局变量:
static System.Threading.Mutex appMutex;
Main 方法里的内容:
string exeName = "OfflineServer"; string globalMutexName = @"Global" + exeName; string appName = "服务程序"; bool createNew; appMutex = new System.Threading.Mutex(true, globalMutexName, out createNew); if (!createNew) { appMutex.Close(); appMutex = null; MessageBox.Show(appName + "已开启,进程为" + exeName + "!", "提示"); return; } Application.ApplicationExit += new EventHandler(OnApplicationExit);
static class Program 里的全其它方法:
static void OnApplicationExit(object sender, EventArgs e) { RelMutex(); } /// <summary> /// 释放 /// </summary> public static void RelMutex() { try { if (appMutex != null) { appMutex.ReleaseMutex(); appMutex.Close(); } } catch (Exception expMu) { } }
-