如何处置System.Diagnostics.Process对象而不终止进程



我有一个应用程序,它创建Process对象以启动外部应用程序。一旦它验证了应用程序已经正确启动,它就不再关心它了,所以我不再需要Process对象,但是我不能对它调用Dispose(),因为我不想关闭进程。解决这个问题的方法是什么?

您可以安全地处置流程实例,之后流程将运行。

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实例并在进程实际终止之前处理它们的原因之一:您将失去停止操作系统进程或查询其状态的控制句柄。除非您有无数的Process实例,否则我不应该担心它们。

我认为Process.Close()Process.Dispose() 杀死进程。它们只是释放一些连接到处理进程的资源。

参考来源:

protected override void Dispose(bool disposing) {
    if( !disposed) {
        if (disposing) {
            //Dispose managed and unmanaged resources
            Close();
        }
        this.disposed = true;
        base.Dispose(disposing);                
    }            
}

public void Close() {
    if (Associated) {
        if (haveProcessHandle) {
            StopWatchingForExit();
            Debug.WriteLineIf(processTracing.TraceVerbose, "Process - CloseHandle(process) in Close()");
            m_processHandle.Close();
            m_processHandle = null;
            haveProcessHandle = false;
        }
        haveProcessId = false;
        isRemoteMachine = false;
        machineName = ".";
        raisedOnExited = false;
        //Don't call close on the Readers and writers
        //since they might be referenced by somebody else while the 
        //process is still alive but this method called.
        standardOutput = null;
        standardInput = null;
        standardError = null;
        output = null;
        error = null;
        Refresh();
    }
}

最新更新