Force Single Instance with Mutex handling restart application

前端 未结 4 1990
[愿得一人]
[愿得一人] 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:25

    I'm not sure what exactly goes wrong in your case but some issues might be:

    • You should probably use try finally to close the mutex to maximize changes of proper cleanup
    • In case cleanup failed previous time then Mutex.WaitOne will throw an AbandonedMutexException instead of return true. In this case your code will exit with an error box while you can just continue.
    • You are giving the Mutex 5 seconds to get aquired. If your shutdown will take over 5 seconds then the next startup will fail. A better option might be to release mutex right before initiating shutdown. (Provided of course that the Mutex is there only for user convenience).

    example

    the following example will require that you use Program.Restart to restart the application. Else the time window can still be the problem.

    static class Program
    {
        private static Mutex _mutex;
    
        [STAThread]
        static void Main()
        {
            _mutex = new Mutex(false, "myprogramkey");
            try
            {
                try
                {
                    if (!_mutex.WaitOne(1))
                    {
                        _mutex.Dispose();
                        _mutex = null;
                        MessageBox.Show("Error!");
                        return;
                    }
                }
                catch (AbandonedMutexException) { /* Mutex wasn't property released last time.*/ }
    
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
            finally
            {
                if (_mutex != null)
                {
                    _mutex.ReleaseMutex();
                    _mutex.Dispose();
                }
            }
        }
    
        public static void Restart()
        {
            if (_mutex != null)
            {
                _mutex.ReleaseMutex();
                _mutex.Dispose();
                _mutex = null;
                Application.Restart();
            }
        }
    }
    

提交回复
热议问题