Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dispose a System.Diagnostics.Process object without killing process?

Tags:

c#

.net

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?

like image 726
amnesia Avatar asked Dec 10 '22 23:12

amnesia


2 Answers

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();
    }
}

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.

like image 191
g.pickardou Avatar answered May 28 '23 14:05

g.pickardou


I think that Process.Close() and Process.Dispose() don't kill the process. They simply release some resources connected to handling the process.

From the reference source:

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

and

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();
    }
}

I don't see anything that should kill the process.

like image 23
xanatos Avatar answered May 28 '23 14:05

xanatos