【问题标题】:C# mutex issue to prevent second instance防止第二个实例的 C# 互斥锁问题
【发布时间】:2011-06-22 00:52:09
【问题描述】:

我遇到了一个有趣的问题(C#/WPF 应用程序)。我正在使用此代码来防止我的应用程序的第二个实例运行。

Mutex _mutex;
string mutexName = "Global\\{SOME_GUID}";
            try
            {
                _mutex = new Mutex(false, mutexName);
            }
            catch (Exception)
            {
//Possible second instance, do something here.
            }

            if (_mutex.WaitOne(0, false))
            {
                base.OnStartup(e);  
            }
            else
            {
            //Do something here to close the second instance
            }

如果我将代码直接放在 OnStartup 方法下的主 exe 中,它可以工作。但是,如果我包装相同的代码并将其放入单独的程序集/dll 并从 OnStartup 方法调用该函数,它不会检测到第二个实例。

有什么建议吗?

【问题讨论】:

    标签: c# multithreading mutex


    【解决方案1】:

    什么是_mutex 变量的生命周期,当它被放置到Dll 时?也许它在 OnStartup 退出后被销毁。将 Single Instance 包装类保留为您的应用程序类成员,与原始 _mutex 变量具有相同的生命周期。

    【讨论】:

    • 谢谢亚历克斯,这就是问题所在。现在感觉有点尴尬,这是我的一个牛仔错误:(
    【解决方案2】:
    static bool IsFirstInstance()
    {
        // First attempt to open existing mutex, using static method: Mutex.OpenExisting
        // It would fail and raise an exception, if mutex cannot be opened (since it didn't exist)
        // And we'd know this is FIRST instance of application, would thus return 'true'
    
        try
        {
            SingleInstanceMutex = Mutex.OpenExisting("SingleInstanceApp");
        }
        catch (WaitHandleCannotBeOpenedException)
        {
            // Success! This is the first instance
            // Initial owner doesn't really matter in this case...
           SingleInstanceMutex = new Mutex(false, "SingleInstanceApp");
    
            return true;
        }
    
        // No exception? That means mutex ALREADY existed!
        return false;
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 2011-08-05
      • 1970-01-01
      • 2010-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多