4

我有许多读取 xml 文件的服务。为了确保没有冲突,我使用互斥锁。无论出于何种原因,如果我的所有服务都由同一用户运行,则没有问题。但是,如果有不同的用户运行这些服务,即使一个服务释放了互斥锁,另一个服务在调用 enter route mutex 时也会出现以下异常“Unhandled Exception: System.TypeInitializationException: The type initializer for 'createMutex.Program' throw an an异常。---> System.UnauthorizedAccessException:对路径“RETEST_MUTEX”的访问被拒绝。”

    public static readonly String ROUTE_MUTEX_STRING = "RETEST_MUTEX";
    private static Mutex _routeMutex = new Mutex(false, ROUTE_MUTEX_STRING);

    /// <summary>
    /// Thin wrapper around the static routeMutex WaitOne method
    /// Always call ExitRouteMutex when done in protected area
    /// </summary>
    /// <param name="millis_timeout"></param>
    /// <returns>true if signaled, like WaitOne</returns>
    public static bool EnterRouteMutex(int millis_timeout)
    {
        try
        {
            return _routeMutex.WaitOne(millis_timeout, false);
        }
        catch (AbandonedMutexException ame)
        {
            // swallow this exception - don't want to depend on other apps being healthy - like pre .NET 2.0 behavior
            // data integrity will be checked
            return _routeMutex.WaitOne(millis_timeout, false);
        }

    }

    public static void ExitRouteMutex()
    {
        try
        {
            _routeMutex.ReleaseMutex();
        }
        catch (ApplicationException)
        {
            // swallow, reduce complexity to client
        }
    }

    static void Main(string[] args)
    {
        Console.WriteLine("Start");
        bool get = EnterRouteMutex(1000);
        System.Console.WriteLine("Mutex created Press enter " + get.ToString());
        Console.ReadLine();            
        ExitRouteMutex();
        Console.WriteLine("Mutex Release");
        System.Console.WriteLine("Press enter");
        Console.ReadLine();
    }
4

1 回答 1

3

这是一个执行跨进程互斥锁的示例。

http://msdn.microsoft.com/en-us/library/c41ybyt3.aspx

它处理 Mutex.OpenExisting 的使用,还演示了 cdhowie 提到的安全方面。

于 2012-12-26T22:32:09.970 回答