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

前端 未结 8 690
温柔的废话
温柔的废话 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:45

    This example will exit after 5 seconds if another instance is already running.

    // unique id for global mutex - Global prefix means it is global to the machine
    const string mutex_id = "Global\\{B1E7934A-F688-417f-8FCB-65C3985E9E27}";
    
    static void Main(string[] args)
    {
    
        using (var mutex = new Mutex(false, mutex_id))
        {
            try
            {
                try
                {
                    if (!mutex.WaitOne(TimeSpan.FromSeconds(5), false))
                    {
                        Console.WriteLine("Another instance of this program is running");
                        Environment.Exit(0);
                    }
                }
                catch (AbandonedMutexException)
                {
                    // Log the fact the mutex was abandoned in another process, it will still get aquired
                }
    
                // Perform your work here.
            }
            finally
            {
                mutex.ReleaseMutex();
            }
        }
    }
    

提交回复
热议问题