问题描述
我有一个创建Process对象以启动外部应用程序的应用程序.一旦它验证了应用程序已正确启动,就不再在乎它了,因此不再需要Process对象,但是由于不想关闭进程,所以无法对其调用Dispose().解决方法是什么?
I have an application that creates Process objects in order to launch external applications. Once it verifies the application has launched correctly, it no longer cares about it, so I don't need the Process object any longer, but I can't call Dispose() on it because I don't want to shutdown the process. What is the workaround for this?
推荐答案
您可以安全地处理流程实例,该流程将在之后运行.
You can safely Dispose the process instance, the process will run after.
class Program
{
static void Main(string[] args)
{
Process p = new Process
{
StartInfo = {FileName = "notepad.exe"}
};
p.Start();
p.Dispose();
// Notepad still runs...
GC.Collect(); // Just for the diagnostics....
// Notepad still runs...
Console.ReadKey();
}
}
实际上,该过程(Notepad.exe)甚至会在您的.NET应用终止后运行.顺便说一句,这是我建议不要担心Process实例并在实际终止之前将其处置的原因之一:您将失去控制手柄以停止OS进程或查询其状态.除非您有无数的Process实例,否则我不必担心它们.
Actually the process (Notepad.exe) will even run after your .NET app was terminated. Btw that's one of the reason I recommend not to worry about the Process instances and disposing them before the process actually terminated: You will lost your control handle to stop the OS processes or query their status. Unless you have zillion of Process instances I should not worry about them.
这篇关于如何在不终止进程的情况下处理System.Diagnostics.Process对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!