runliuv

runliuv@cnblogs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

 本机只允许创建一个实例

 

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) { }
        }

 

 

-

posted on 2019-10-12 17:06  runliuv  阅读(534)  评论(0编辑  收藏  举报