What is a good pattern for using a Global Mutex in C#?

前端 未结 8 697
温柔的废话
温柔的废话 2020-11-21 23:16

The Mutex class is very misunderstood, and Global mutexes even more so.

What is good, safe pattern to use when creating Global mutexes?

One that will work

8条回答
  •  遇见更好的自我
    2020-11-21 23:53

    A solution (for WPF) without WaitOne because it can cause an AbandonedMutexException. This solution uses the Mutex constructor that returns the createdNew boolean to check if the mutex is already created. It also uses the GetType().GUID so renaming an executable doesn't allow multiple instances.

    Global vs local mutex see note in: https://docs.microsoft.com/en-us/dotnet/api/system.threading.mutex?view=netframework-4.8

    private Mutex mutex;
    private bool mutexCreated;
    
    public App()
    {
        string mutexId = $"Global\\{GetType().GUID}";
        mutex = new Mutex(true, mutexId, out mutexCreated);
    }
    
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        if (!mutexCreated)
        {
            MessageBox.Show("Already started!");
            Shutdown();
        }
    }
    

    Because Mutex implements IDisposable it is released automatically but for completeness call dispose:

    protected override void OnExit(ExitEventArgs e)
    {
        base.OnExit(e);
        mutex.Dispose();
    }
    

    Move everything into a base class and add the allowEveryoneRule from the accepted answer. Also added ReleaseMutex though it doesn't look like it's really needed because it is released automatically by the OS (what if the application crashes and never calls ReleaseMutex would you need to reboot?).

    public class SingleApplication : Application
    {
        private Mutex mutex;
        private bool mutexCreated;
    
        public SingleApplication()
        {
            string mutexId = $"Global\\{GetType().GUID}";
    
            MutexAccessRule allowEveryoneRule = new MutexAccessRule(
                new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                MutexRights.FullControl, 
                AccessControlType.Allow);
            MutexSecurity securitySettings = new MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);
    
            // initiallyOwned: true == false + mutex.WaitOne()
            mutex = new Mutex(initiallyOwned: true, mutexId, out mutexCreated, securitySettings);        
        }
    
        protected override void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);
            if (mutexCreated)
            {
                try
                {
                    mutex.ReleaseMutex();
                }
                catch (ApplicationException ex)
                {
                    MessageBox.Show(ex.Message, ex.GetType().FullName, MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            mutex.Dispose();
        }
    
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            if (!mutexCreated)
            {
                MessageBox.Show("Already started!");
                Shutdown();
            }
        }
    }
    

提交回复
热议问题