2009-04-22 14 views
8

我有一个.NET应用程序,我只允许一次运行一个进程,但是该应用程序在Citrix计算机上不时使用,因此可以由同一台计算机上的多个用户运行。如何检查每个用户会话的正在运行的进程?

我想检查并确保应用程序仅在每个用户会话中运行一次,因为现在如果用户A正在运行该应用程序,则用户B将收到“应用程序已在使用中”的消息,而不应该这样做。

这是我现在有一个检查正在运行的进程:

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

编辑:改进了答案根据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 - 您可以使其取决于用户。

也许你喜欢阅读这篇文章:the misunderstood mutex

+0

为我工作。谢谢! – Russ 2009-04-22 15:50:24

3

由于tanascius已经说了,你可以使用互斥。

在运行终端服务的服务器上,已命名的系统互斥可以具有两个可见级别。如果其名称以前缀“Global \”开头,则互斥体在所有终端服务器会话中都可见。如果其名称以前缀“Local \”开头,则该互斥体仅在创建它的终端服务器会话中可见。

来源:msdn, Mutex Class

0

如果Form1的推出非后台线程,而Form1中退出时,你已经有了一个问题:互斥体被释放,但这个过程仍然存在。下面沿着线的东西是更好恕我直言:

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 - 只需测试SessionId

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)

相关问题