【发布时间】:2011-06-17 21:26:36
【问题描述】:
有人可以说明如何检查程序的另一个实例(例如 test.exe)是否正在运行,如果存在则停止加载应用程序。
【问题讨论】:
-
@Tim Schmelter 谢谢,但这是一个 GUI 应用程序,我的是一个控制台应用程序
有人可以说明如何检查程序的另一个实例(例如 test.exe)是否正在运行,如果存在则停止加载应用程序。
【问题讨论】:
想要一些严肃的代码吗?这里是。
var exists = System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1;
这适用于任何应用程序(任何名称),如果有另一个实例在运行相同应用程序,它将变为true。
编辑:要解决您的需求,您可以使用以下任何一种:
if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1) return;
从您的 Main 方法退出该方法...或
if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1) System.Diagnostics.Process.GetCurrentProcess().Kill();
这将立即终止当前的加载过程。
您需要为.Count()扩展方法添加对System.Core.dll的引用。或者,您可以使用.Length 属性。
【讨论】:
.Count > 1。
不确定您所说的“程序”是什么意思,但如果您想将应用程序限制为一个实例,那么您可以使用互斥锁来确保您的应用程序尚未运行。
[STAThread]
static void Main()
{
Mutex mutex = new System.Threading.Mutex(false, "MyUniqueMutexName");
try
{
if (mutex.WaitOne(0, false))
{
// Run the application
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
else
{
MessageBox.Show("An instance of the application is already running.");
}
}
finally
{
if (mutex != null)
{
mutex.Close();
mutex = null;
}
}
}
【讨论】:
这里有一些很好的示例应用程序。以下是一种可能的方法。
public static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName (current.ProcessName);
//Loop through the running processes in with the same name
foreach (Process process in processes)
{
//Ignore the current process
if (process.Id != current.Id)
{
//Make sure that the process is running from the exe file.
if (Assembly.GetExecutingAssembly().Location.
Replace("/", "\\") == current.MainModule.FileName)
{
//Return the other process instance.
return process;
}
}
}
//No other instance was found, return null.
return null;
}
if (MainForm.RunningInstance() != null)
{
MessageBox.Show("Duplicate Instance");
//TODO:
//Your application logic for duplicate
//instances would go here.
}
许多其他可能的方式。请参阅替代方案示例。
编辑 1:刚刚看到您有一个控制台应用程序的评论。 second sample.
对此进行了讨论【讨论】:
Process 静态类有一个 GetProcessesByName() 方法,您可以使用它来搜索正在运行的进程。只需搜索具有相同可执行名称的任何其他进程。
【讨论】:
你可以试试这个
Process[] processes = Process.GetProcessesByName("processname");
foreach (Process p in processes)
{
IntPtr pFoundWindow = p.MainWindowHandle;
// Do something with the handle...
//
}
【讨论】: