我有一个 .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
}
EDIT:根据改进答案这个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();
}
}
重要的是AppGuid
- 你可以让它取决于用户。
也许您喜欢阅读这篇文章:被误解的互斥体
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)