2009-04-22 12 views
8

私は、一度に1つのプロセスしか実行できない.NETアプリケーションを持っていますが、アプリケーションはCitrixボックスで時折使用されるため、同じマシン上の複数のユーザーが実行できます。ユーザーセッションごとに実行中のプロセスを確認するにはどうすればよいですか?

ユーザーAが現在アプリケーションを実行している場合、ユーザーBが「App already in use」メッセージを取得していないため、アプリケーションがユーザーセッションごとに1回だけ実行されていることを確認してください。

これは私が今実行中のプロセスをチェックしていること持っているものです。

Process[] p = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName); 
      if (p.Length > 1) 
      { 
#if !DEBUG 
       allowedToOpen &= false; 
       errorMessage += 
        string.Format("{0} is already running.{1}", Constants.AssemblyTitle, Environment.NewLine); 
#endif 
      } 

答えて

6

EDIT:あなたは天気をチェックするためにミューテックスを使用することができます... this cw questionに応じ

を答えを改善しましたアプリは既に実行されています:

using(var mutex = new Mutex(false, AppGuid)) 
{ 
    try 
    { 
     try 
     { 
      if(!mutex.WaitOne(0, false)) 
      { 
       MessageBox.Show("Another instance is already running."); 
       return; 
      } 
     } 
     catch(AbandonedMutexException) 
     { 
      // Log the fact the mutex was abandoned in another process, 
      // it will still get aquired 
     } 

     Application.Run(new Form1()); 
    } 
    finally 
    { 
     mutex.ReleaseMutex(); 
    } 
} 

重要なのはAppGuidです。これはユーザーによって異なる場合があります。 tanasciusがすでに言ったようthe misunderstood mutex

+0

私のために動作します。ありがとう! – Russ

3

、あなたがミューテックスを使用することができます。

はたぶん、あなたはこの記事を読むのが好き。

ターミナルサービスを実行しているサーバーでは、名前付きシステムミューテックスは2つのレベルの可視性を持つことができます。その名前が接頭辞 "Global \"で始まる場合、mutexはすべてのターミナルサーバーセッションで表示されます。その名前が接頭辞 "Local \"で始まる場合、mutexは作成されたターミナルサーバーセッションでのみ表示されます。

出典:ミューテックスを解放が、プロセスはまだそこにあるされています

0

Form1が非バックグラウンドスレッドを起動し、Form1が終了していること、あなたが問題を持っていればmsdn, Mutex Class。ミューテックスがいる限り、プライマリアプリケーションドメインがアップまだあるとしてリリースされることはありません

static class Program { 
    private static Mutex mutex; 



    /// <summary> 
    /// The main entry point for the application. 
    /// </summary> 
    [STAThread] 
    static void Main() { 
     bool createdNew = true; 
     mutex = new Mutex(true, @"Global\Test", out createdNew); 
     if (createdNew) { 
      Application.EnableVisualStyles(); 
      Application.SetCompatibleTextRenderingDefault(false); 
      Application.Run(new Form1());   
     } 
     else { 
      MessageBox.Show(
       "Application is already running", 
       "Error", 
       MessageBoxButtons.OK, 
       MessageBoxIcon.Error 
      ); 
     } 
    } 
} 

:以下の線に沿って何かが良く私見です。アプリケーションが実行されている間は、そのようになります。

0

通常、Mutexがより良い解決策と考えられますが、もテストするだけで、セッションごとの単一インスタンスの問題を解決できます。Mutex

private static bool ApplicationIsAlreadyRunning() 
    { 
     var currentProcess = Process.GetCurrentProcess(); 
     var processes = Process.GetProcessesByName(currentProcess.ProcessName); 

     // test if there's another process running in current session. 
     var intTotalRunningInCurrentSession = processes.Count(prc => prc.SessionId == currentProcess.SessionId); 

     return intTotalRunningInCurrentSession > 1; 
    } 

Source (no Linq)

関連する問題