2011-06-21 12 views
0

興味深い問題がありました(C#/ WPFアプリケーション)。このコードを使用して、アプリケーションの2番目のインスタンスが実行されないようにしています。2番目のインスタンスを防ぐための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メソッドから呼び出すと、2番目のインスタンスが検出されません。

提案がありますか?

答えて

1

変数ライフタイムは、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; 
} 
関連する問題