在C#中使用全局Mutex的好模式是什么?

405

Mutex类非常被误解,全局互斥量更是如此。

创建全局互斥量时,有哪些好的、安全的模式可以使用?

一个能够正常工作的模式应该:

  • 不考虑我的机器所在的区域设置
  • 能够保证适当地释放互斥量
  • 可选地,在未获取到互斥量时不会永远挂起
  • 处理其他进程放弃互斥量的情况
7个回答

442

我希望能够明确这一点,因为这非常难以做到:

using System.Runtime.InteropServices;   //GuidAttribute
using System.Reflection;                //Assembly
using System.Threading;                 //Mutex
using System.Security.AccessControl;    //MutexAccessRule
using System.Security.Principal;        //SecurityIdentifier

static void Main(string[] args)
{
    // get application GUID as defined in AssemblyInfo.cs
    string appGuid =
        ((GuidAttribute)Assembly.GetExecutingAssembly().
            GetCustomAttributes(typeof(GuidAttribute), false).
                GetValue(0)).Value.ToString();

    // unique id for global mutex - Global prefix means it is global to the machine
    string mutexId = string.Format( "Global\\{{{0}}}", appGuid );

    // Need a place to store a return value in Mutex() constructor call
    bool createdNew;

    // edited by Jeremy Wiebe to add example of setting up security for multi-user usage
    // edited by 'Marc' to work also on localized systems (don't use just "Everyone") 
    var allowEveryoneRule =
        new MutexAccessRule( new SecurityIdentifier( WellKnownSidType.WorldSid
                                                   , null)
                           , MutexRights.FullControl
                           , AccessControlType.Allow
                           );
    var securitySettings = new MutexSecurity();
    securitySettings.AddAccessRule(allowEveryoneRule);

   // edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen
    using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings))
    {
        // edited by acidzombie24
        var hasHandle = false;
        try
        {
            try
            {
                // note, you may want to time out here instead of waiting forever
                // edited by acidzombie24
                // mutex.WaitOne(Timeout.Infinite, false);
                hasHandle = mutex.WaitOne(5000, false);
                if (hasHandle == false)
                    throw new TimeoutException("Timeout waiting for exclusive access");
            }
            catch (AbandonedMutexException)
            {
                // Log the fact that the mutex was abandoned in another process,
                // it will still get acquired
                hasHandle = true;
            }

            // Perform your work here.
        }
        finally
        {
            // edited by acidzombie24, added if statement
            if(hasHandle)
                mutex.ReleaseMutex();
        }
    }
}

1
你可能想要省略using来检查createdNew,并在finally中添加mutex.Dispose()。我现在无法清楚地解释(我不知道原因),但我已经遇到了这样一种情况:当我在当前的AppDomain中获取互斥锁,然后加载一个新的AppDomain并从其中执行相同的代码时,mutex.WaitOne返回true,而createdNew变为false - Sergey.quixoticaxis.Ivanov
  1. exitContext = falsemutex.WaitOne(5000, false) 中有什么作用?看起来只会在 CoreCLR 中引发一个断言
  2. 如果有人想知道,在 Mutex 的构造函数中,initiallyOwned 为什么是 false 部分原因可以参考这篇 MSDN 文章
- jrh
5
提示:注意在ASP.NET中使用Mutex:“Mutex类强制执行线程标识,因此只有获取它的线程才能释放互斥锁。相比之下,Semaphore类不强制执行线程标识。”一个ASP.NET请求可以由多个线程提供服务。 - Sam Rueby
如何在VB.NET中安全地处理“startupnextinstance”事件?而不是在C#中。请参考以下链接:https://learn.microsoft.com/es-es/dotnet/api/microsoft.visualbasic.applicationservices.windowsformsapplicationbase.startupnextinstance?view=netframework-4.8 - Kiquenet
1
在Unix系统中是否有相应的模式呢? (MutexAccessRule、MutexRights、MutexSecurity实现仅适用于Windows) - Zander Fick
显示剩余4条评论

144

使用被接受的答案,我创建了一个辅助类,这样你就可以像使用Lock语句一样使用它。只是想分享一下。

用法:

using (new SingleGlobalInstance(1000)) //1000ms timeout on global lock
{
    //Only 1 of these runs at a time
    RunSomeStuff();
}

还有一个帮助类:

class SingleGlobalInstance : IDisposable
{
    //edit by user "jitbit" - renamed private fields to "_"
    public bool _hasHandle = false;
    Mutex _mutex;

    private void InitMutex()
    {
        string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value;
        string mutexId = string.Format("Global\\{{{0}}}", appGuid);
        _mutex = new Mutex(false, mutexId);

        var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
        var securitySettings = new MutexSecurity();
        securitySettings.AddAccessRule(allowEveryoneRule);
        _mutex.SetAccessControl(securitySettings);
    }

    public SingleGlobalInstance(int timeOut)
    {
        InitMutex();
        try
        {
            if(timeOut < 0)
                _hasHandle = _mutex.WaitOne(Timeout.Infinite, false);
            else
                _hasHandle = _mutex.WaitOne(timeOut, false);

            if (_hasHandle == false)
                throw new TimeoutException("Timeout waiting for exclusive access on SingleInstance");
        }
        catch (AbandonedMutexException)
        {
            _hasHandle = true;
        }
    }


    public void Dispose()
    {
        if (_mutex != null)
        {
            if (_hasHandle)
                _mutex.ReleaseMutex();
            _mutex.Close();
        }
    }
}

1
从语义上讲,(new SingleGlobalInstance(xxx))会让人误以为每个互斥量都是不同的,而实际上它们都指向同一个互斥量。创建一个'using (new MutexLocker(Mutex mutexOpt = null)"可能更清晰,在其中创建/默认到一个静态互斥量,该互斥量在每个应用程序中仅创建一次(可能隐藏在类中,就像您所做的那样)。另外,“Global”通常意味着“应用程序范围”,而“System”是“服务器范围”,这我认为是命名互斥量的情况。http://msdn.microsoft.com/en-us/library/hw29w7t1.aspx - crokusek
3
如何处理消耗SingleGlobalInstance的类中的超时异常?同时,在构造一个实例时抛出异常是否是良好的实践? - kiran
4
超时时间为0仍应为0,而非无限大!更好的方法是检查“< 0”而不是“<= 0”。 - ygoe
3
我发现在Dispose方法中使用"_mutex.Close()"而不是"_mutex.Dispose()"对我有用。 错误是由于尝试处理底层WaitHandle引起的。 "Mutex.Close()"处置了底层资源。 - djpMusic
1
当我尝试打开应用程序的第二个实例时,它会显示“AppName已停止工作”。我想在用户尝试打开应用程序的第二个实例时将焦点设置在应用程序上。我该如何做? - Bhaskar
显示剩余4条评论

10

如果另一个实例已经在运行,此示例将在5秒后退出。

// 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();
        }
    }
}

10

无论是 Mutex 还是 WinApi CreateMutex() 都对我无效。

另一种解决方案:

static class Program
{
    [STAThread]
    static void Main()
    {
        if (SingleApplicationDetector.IsRunning()) {
            return;
        }

        Application.Run(new MainForm());

        SingleApplicationDetector.Close();
    }
}

还有 SingleApplicationDetector

using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Threading;

public static class SingleApplicationDetector
{
    public static bool IsRunning()
    {
        string guid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
        var semaphoreName = @"Global\" + guid;
        try {
            __semaphore = Semaphore.OpenExisting(semaphoreName, SemaphoreRights.Synchronize);

            Close();
            return true;
        }
        catch (Exception ex) {
            __semaphore = new Semaphore(0, 1, semaphoreName);
            return false;
        }
    }

    public static void Close()
    {
        if (__semaphore != null) {
            __semaphore.Close();
            __semaphore = null;
        }
    }

    private static Semaphore __semaphore;
}

使用 Semaphore 而不是 Mutex 的原因:

Mutex 类强制执行线程身份,因此只有获取它的线程才能释放互斥体。相比之下,Semaphore 类不强制执行线程身份。

<< System.Threading.Mutex

参考文献:Semaphore.OpenExisting()


9
Semaphore.OpenExistingnew Semaphore之间存在可能的竞态条件。 - xmedeko
为解决这个问题,您可以在try/catch/finally的finally块中简单地包含释放操作。这可以确保您的互斥锁不会永远保持打开状态。 - Ro Yo Mi

4
有时通过示例学习是最有帮助的。在三个不同的控制台窗口中运行此控制台应用程序。您会发现,您首先运行的应用程序首先获取互斥锁,而其他两个应用程序正在等待它们的轮到。然后在第一个应用程序中按Enter键,您会发现应用程序2现在通过获取互斥锁而继续运行,但是应用程序3正在等待其轮到。在应用程序2中按Enter键后,您会看到应用程序3继续运行。这说明了互斥锁保护代码段只能由一个线程(在本例中为进程)执行的概念,例如写入文件。
using System;
using System.Threading;

namespace MutexExample
{
    class Program
    {
        static Mutex m = new Mutex(false, "myMutex");//create a new NAMED mutex, DO NOT OWN IT
        static void Main(string[] args)
        {
            Console.WriteLine("Waiting to acquire Mutex");
            m.WaitOne(); //ask to own the mutex, you'll be queued until it is released
            Console.WriteLine("Mutex acquired.\nPress enter to release Mutex");
            Console.ReadLine();
            m.ReleaseMutex();//release the mutex so other processes can use it
        }
    }
}

enter image description here


4

一种(适用于WPF)没有使用WaitOne的解决方案,因为它可能会导致AbandonedMutexException异常。此解决方案使用Mutex构造函数,返回createdNew布尔值以检查mutex是否已创建。它还使用GetType().GUID,因此重命名可执行文件不允许多个实例。

全局与本地mutex,请参见注释: https://learn.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();
    }
}

因为Mutex实现了IDisposable接口,所以它会自动释放,但为了完整性,请调用dispose:

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

将所有东西移到一个基类中,并添加来自已接受答案的allowEveryoneRule。还添加了ReleaseMutex,尽管它看起来似乎并不需要,因为它会被操作系统自动释放(如果应用程序崩溃并且没有调用ReleaseMutex,那么需要重新启动吗?)。
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();
        }
    }
}

0

全局互斥锁不仅用于确保应用程序只有一个实例。我个人更喜欢使用Microsoft.VisualBasic来确保单实例应用程序,就像What is the correct way to create a single-instance WPF application?(Dale Ragan的答案)中所描述的那样...我发现这样更容易将新应用程序启动时接收到的参数传递给初始单实例应用程序。

但是关于此线程中的一些先前代码,我宁愿不每次都创建互斥锁以便对其进行锁定。对于单实例应用程序来说可能还好,但在其他用途中,我认为这样做有点过度杀伤力。

这就是为什么我建议使用以下实现方式:

用法:

static MutexGlobal _globalMutex = null;
static MutexGlobal GlobalMutexAccessEMTP
{
    get
    {
        if (_globalMutex == null)
        {
            _globalMutex = new MutexGlobal();
        }
        return _globalMutex;
    }
}

using (GlobalMutexAccessEMTP.GetAwaiter())
{
    ...
}   

互斥锁全局包装器:

using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Threading;

namespace HQ.Util.General.Threading
{
    public class MutexGlobal : IDisposable
    {
        // ************************************************************************
        public string Name { get; private set; }
        internal Mutex Mutex { get; private set; }
        public int DefaultTimeOut { get; set; }
        public Func<int, bool> FuncTimeOutRetry { get; set; }

        // ************************************************************************
        public static MutexGlobal GetApplicationMutex(int defaultTimeOut = Timeout.Infinite)
        {
            return new MutexGlobal(defaultTimeOut, ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value);
        }

        // ************************************************************************
        public MutexGlobal(int defaultTimeOut = Timeout.Infinite, string specificName = null)
        {
            try
            {
                if (string.IsNullOrEmpty(specificName))
                {
                    Name = Guid.NewGuid().ToString();
                }
                else
                {
                    Name = specificName;
                }

                Name = string.Format("Global\\{{{0}}}", Name);

                DefaultTimeOut = defaultTimeOut;

                FuncTimeOutRetry = DefaultFuncTimeOutRetry;

                var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                var securitySettings = new MutexSecurity();
                securitySettings.AddAccessRule(allowEveryoneRule);

                Mutex = new Mutex(false, Name, out bool createdNew, securitySettings);

                if (Mutex == null)
                {
                    throw new Exception($"Unable to create mutex: {Name}");
                }
            }
            catch (Exception ex)
            {
                Log.Log.Instance.AddEntry(Log.LogType.LogException, $"Unable to create Mutex: {Name}", ex);
                throw;
            }
        }

        // ************************************************************************
        /// <summary>
        /// 
        /// </summary>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public MutexGlobalAwaiter GetAwaiter(int timeOut)
        {
            return new MutexGlobalAwaiter(this, timeOut);
        }

        // ************************************************************************
        /// <summary>
        /// 
        /// </summary>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public MutexGlobalAwaiter GetAwaiter()
        {
            return new MutexGlobalAwaiter(this, DefaultTimeOut);
        }

        // ************************************************************************
        /// <summary>
        /// This method could either throw any user specific exception or return 
        /// true to retry. Otherwise, retruning false will let the thread continue
        /// and you should verify the state of MutexGlobalAwaiter.HasTimedOut to 
        /// take proper action depending on timeout or not. 
        /// </summary>
        /// <param name="timeOutUsed"></param>
        /// <returns></returns>
        private bool DefaultFuncTimeOutRetry(int timeOutUsed)
        {
            // throw new TimeoutException($"Mutex {Name} timed out {timeOutUsed}.");

            Log.Log.Instance.AddEntry(Log.LogType.LogWarning, $"Mutex {Name} timeout: {timeOutUsed}.");
            return true; // retry
        }

        // ************************************************************************
        public void Dispose()
        {
            if (Mutex != null)
            {
                Mutex.ReleaseMutex();
                Mutex.Close();
            }
        }

        // ************************************************************************

    }
}

等待者
using System;

namespace HQ.Util.General.Threading
{
    public class MutexGlobalAwaiter : IDisposable
    {
        MutexGlobal _mutexGlobal = null;

        public bool HasTimedOut { get; set; } = false;

        internal MutexGlobalAwaiter(MutexGlobal mutexEx, int timeOut)
        {
            _mutexGlobal = mutexEx;

            do
            {
                HasTimedOut = !_mutexGlobal.Mutex.WaitOne(timeOut, false);
                if (! HasTimedOut) // Signal received
                {
                    return;
                }
            } while (_mutexGlobal.FuncTimeOutRetry(timeOut));
        }

        #region IDisposable Support
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    _mutexGlobal.Mutex.ReleaseMutex();
                }

                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                // TODO: set large fields to null.

                disposedValue = true;
            }
        }
        // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
        // ~MutexExAwaiter()
        // {
        //   // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
        //   Dispose(false);
        // }

        // This code added to correctly implement the disposable pattern.
        public void Dispose()
        {
            // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
            Dispose(true);
            // TODO: uncomment the following line if the finalizer is overridden above.
            // GC.SuppressFinalize(this);
        }
        #endregion
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接