2011-01-11 12 views
1

ユーザーセッションごとにSigleInstanceアプリケーションを実装しようとしています。私はこれにローカルミューテックスを使用しています。私は次のスタートアップコードを持っています。なぜMutex.WaitOne()はすぐにWPFで返されますか?

public partial class App : Application 
{ 
    private const string applicationName = "EDisc.Client.Application"; 
    private const string appGUID = "2AE55EA7-B392-42EF-BDFA-3DAFCE2B4B32"; 
    public App() 
    { 
     bool isUnique = false; 
     using (var mutex = new Mutex(false, appGUID)) //Local mutex is local to the machine,it is per user,If u need a instance per machine,prefix appGUID with global. 
     { 
      try 
      { 
       try 
       { 
        isUnique = mutex.WaitOne(TimeSpan.FromSeconds(3), true); //wait in case first instance is shutting down. 
        if (isUnique) //If this is the first process. 
        { 
         this.Navigated += new NavigatedEventHandler(App_Navigated); 
         this.Exit += new ExitEventHandler(App_Exit); 
         AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); 
         this.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException); 
        } 
        else  //If process is already running. 
        { 
         LoggingHelper.LogMessage(CommonMessages.ANOTHER_APP_INSTANCE_OPEN, Source.EDiscClientApplication); 
         MessageBox.Show(CommonMessages.CLOSE_OTHER_APP_INSTANCE, CommonMessages.ANOTHER_APP_INSTANCE_OPEN, 
          MessageBoxButton.OK, 
          MessageBoxImage.Exclamation); 
         CloseApplicationInstance(); 
         return; 
        } 
       } 
       catch (AbandonedMutexException) 
       { 

       } 

      } 
      finally 
      { 
       if (isUnique) 
        mutex.ReleaseMutex(); 
      } 
     } 

    } 
} 

isUniqueは、最初のインスタンスか2番目のインスタンスかにかかわらず常にtrueです。 mutex.waitone()は待機せずにすぐに戻ります。私はこのコードで間違っている可能性があることを頭に傷つけてきました。助けてください

答えて

3

あなたのコードは、アプリケーションコンストラクタの最後にミューテックスをリリースしています - あなたはそれらのイベントハンドラを登録しながら数マイクロ秒間だけ取得したままにしておいてください。アプリケーションのシャットダウン時にReleaseMutex()コール(およびusingステートメントによって実行されたDispose()コール)を実行する必要があります。

+0

によって作成された場合はfalseを返しますoutパラメータを確認してください。 – Rohit

0

私は起こっていることは、あなたがconstrutorのfinallyブロックにmutexをリリースしていることです。コンストラクタが終了すると、あなたはmutexを解放します。したがって、アプリケーションの次のインスタンスもこのmutexを取得できます。 あなたは、代わりに試すことができます。

public Mutex( bool initiallyOwned, string name, out bool createdNew )

をですから、mutexがすでにはい、それは多くのことをworks.thanks別のプロセス

関連する問題