我如何检查每个用户会话正在运行的进程? [英] How can I check for a running process per user session?
问题描述
我有一个.net应用程序,我只允许在一次运行一个进程,但是该应用程序上使用思杰箱子不时,因此,可以由多个用户在同一台机器上运行
我要检查,并确保该应用程序是唯一每个用户会话中运行一次,因为现在如果用户A正在运行的应用程序,那么用户B获得的应用程序已在使用中的消息,并且不应该。
这是我现在有一个检查正在运行的进程:
过程[] P = Process.GetProcessesByName(Process.GetCurrentProcess()ProcessName。);
如果(p.Length→1)
{
#如果!DEBUG
allowedToOpen和放大器; = FALSE;
的errorMessage + =
的String.Format({0}已经运行{1},Constants.AssemblyTitle,Environment.NewLine);
#ENDIF
}
编辑:的改进,根据答案<一href="http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c/229567#229567">this CW问题 ...
您可以使用一个互斥体检查阉应用程序已经运行:
使用(VAR互斥=新的mutex(假,APPGUID))
{
尝试
{
尝试
{
如果(!mutex.WaitOne(0,FALSE))
{
的MessageBox.show(另一个实例已经在运行。);
返回;
}
}
赶上(AbandonedMutexException)
{
//登录互斥锁被遗弃在另一个进程的事实,
//它仍然会得到获得性
}
Application.Run(新Form1中());
}
最后
{
mutex.ReleaseMutex();
}
}
重要的是 APPGUID
- 你可以把它取决于用户
也许你喜欢阅读这篇文章:被误解的互斥
I have a .NET application that I only allow to run a single process at a time of, however that app is used on Citrix boxes from time to time, and as such, can be run by multiple users on the same machine.
I want to check and make sure that the application is only running once per user session, because right now if user A is running the app, then user B gets the "App already in use" message, and should not.
This is what I have now that checks for the running process:
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
}
EDIT: Improved the answer according to this cw question ...
You can use a mutex for checking wether the app already runs:
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();
}
}
Important is the AppGuid
- you could make it depend on the user.
Maybe you like to read this article: the misunderstood mutex
这篇关于我如何检查每个用户会话正在运行的进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!