Force Single Instance with Mutex handling restart application

前端 未结 4 1991
[愿得一人]
[愿得一人] 2021-01-25 12:04

I have a problem when i want use mutex to force single instance of my program.

I a winform App with a WebBrowser Control. I need to autorestart if certain conditions ar

4条回答
  •  故里飘歌
    2021-01-25 12:16

    Try using try..finally for managing the Mutex.

    I usually use this approach. Worked well in combination with Application.Restart().

        private const string ApplicationMutexName = "";
    
        /// 
        /// The main entry point for the application.
        /// 
        [STAThread]
        public static void Main()
        {
            RunApplicationPreservingSingleInstance();
        }
    
        private static void RunApplicationPreservingSingleInstance()
        {
            Mutex mutex = AcquireMutex();
            if (mutex == null)
            {
                return;
            }
    
            try
            {
                RunApplication();
            }
            finally
            {
                mutex.ReleaseMutex();
            }
        }
    
        private static Mutex AcquireMutex()
        {
            Mutex appGlobalMutex = new Mutex(false, ApplicationMutexName);
            if (!appGlobalMutex.WaitOne(3000))
            {
                return null;
            }
            return appGlobalMutex;
        }
    
        private static void RunApplication()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    

提交回复
热议问题