我正在使用命名系统互斥锁来同步 2 个进程。这就是我目前在我的应用程序中获取互斥锁的方式:

using System.Threading;

public static bool AcquireMutex()
{
    // Protect against double acquisitions
    if (MyMutex != null)
    {
        throw new ApplicationException("Failed to acquire mutex");
    }

    try
    {
        // See if a named system mutex has already been created - if it has,
        // wait a short amount of time for its release.
        MyMutex = Mutex.OpenExisting(MutexName);
        if (!MyMutex.WaitOne(TimeSpan.FromSeconds(2), false))
        {
            // MyMutex still being held
            MyMutex = null;
            return false;
        }
    }
    catch
    {
        // MyMutex doesn't exist so create it
        MyMutex = new Mutex(true, MutexName);
    }

    return true;
}

如果带有 OpenExisting 的命名系统互斥锁不存在,MutexName 将抛出异常,允许我的应用程序创建它。

但是,这里似乎存在竞争条件 - 如果 OpenExisting 抛出,则在调用 new Mutex 之前有一个小窗口,其他应用程序可能已在该窗口获取互斥锁。

避免这种竞争条件并使此代码更可靠的最佳方法是什么?

一位同事提到他在他的代码中使用了 Win32 Platform SDK 中的 CreateMutex(另一个需要同步的进程)。然而,.NET Framework 似乎并不支持它。所以我不确定它是我代码的最佳解决方案。

更新

根据@David Schwartz 的回答,这是我的新代码:
public static bool AcquireMutex()
{
    // Protect against double acquisitions
    if (MyMutex != null)
    {
        throw new ApplicationException("Failed to acquire mutex");
    }

    bool createdNew;
    MyMutex = new Mutex(true, MutexName, out createdNew);
    if (createdNew)
    {
        // Mutex was created so ownership is guaranteed; no need to wait on it.
        return true;
    }

    try
    {
        if (!MyMutex.WaitOne(TimeSpan.FromSeconds(2), false))
        {
            MyMutex = null;
            return false;
        }
    }
    catch (AbandonedMutexException)
    {
        // Other application was aborted, which led to an abandoned mutex.
        // This is fine, as we have still successfully acquired the mutex.
    }

    return true;
}

最佳答案

有一个专门为此目的设计的构造函数。从 docs :

关于c# - 获取互斥锁时如何避免竞争条件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9203594/

10-11 22:54
查看更多