2011-06-21 60 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; 
}