C#利用Mutex实现只运行一个程序实例

时间:2022-08-29 08:02:05
static void Main()
        {
            bool canCreateNew;
           
            //限制单例运行
            Mutex m = new Mutex(true, "AnyName", out canCreateNew);
            if (canCreateNew)
            {
                string filePath = AppDomain.CurrentDomain.BaseDirectory +
                System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".xml";
                if (System.IO.File.Exists(filePath))
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Command.config = new Configurations(filePath);
                    Application.Run(new FormMain());
                }
                else
                {
                    FileHelper.WriteLog(FileHelper.LogType.LTError, "XML not exist");
                }
                m.ReleaseMutex();    //必须
            }
            else
            {
                MessageBox.Show("");
            }
        }