2011-06-21 39 views
0

我有一个有趣的问题(C#/ WPF应用程序)。我正在使用此代码来阻止运行我的应用程序的第二个实例。C#互斥问题,以防止二次

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方法调用该函数,它不检测第二个实例。

有什么建议吗?

回答

1

什么是_mutex变量的生命期,当它被放置到Dll?也许它在OnStartup退出后被销毁。保留单实例包装类作为您的应用程序类成员,以使其具有与原始_mutex变量相同的生存时间。

+0

谢谢亚历克斯,那是个问题。现在感觉有点尴尬,这是我的一个牛仔错误:( –

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