C#互斥问题防止二次实例

时间:2011-06-21 15:19:35

标签: c# multithreading mutex

我遇到了一个有趣的问题(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方法调用该函数,则它不会检测到第二个实例。

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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;
 }