如何检查每个用户会话的运行进程?

Rus*_*uss 8 .net c#

我有一个.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
            }
Run Code Online (Sandbox Code Playgroud)

tan*_*ius 5

编辑:根据这个cw问题改进答案...

您可以使用互斥锁检查应用程序是否已运行:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

重要的是AppGuid- 你可以让它取决于用户.

也许你喜欢读这篇文章:被误解的互斥体