C#使用Mutex实现系统范围内单实例运行的示例代码

  private static void GlobalMutex()
        {
            // 是否第一次创建mutex
            bool newMutexCreated = false;
            string mutexName = "Global\\" + "tenghoo";
            Mutex mutex = null;
            try
            {
                mutex = new Mutex(false, mutexName, out newMutexCreated);
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                System.Threading.Thread.Sleep(3000);
                Environment.Exit(1);
            }

            // 第一次创建mutex
            if (newMutexCreated)
            {
                Console.WriteLine("程序已启动");
               //todo:此处为要执行的任务
            }
            else
            {
                Console.Write("另一个窗口已在运行,3秒以后自动关闭。。");
                System.Threading.Thread.Sleep(1000);
                Console.Write("1");
                System.Threading.Thread.Sleep(1000);
                Console.Write("2");
                System.Threading.Thread.Sleep(1000);
                Console.Write("3");
                Environment.Exit(1);//退出程序
            }
        }

你可能感兴趣的:(C#)