Search code examples
c#processdispose

C# Does Process.Dispose() also cleanup the StandardInput and StandardInput.BaseStream?


Currently working with a process I am starting up and then accessing the StandardInput.BaseStream and then copying a Stream to it. Do I need to Dispose of the StandardInput and/or the StandardInput.BaseStream at all or is that handled with Process.Dispose()?

        Process someProgram = null;
        try
        {
            someProgram = new Process();
            someProgram.StartInfo.RedirectStandardInput = true;
            someProgram.StartInfo.FileName = @"C:\Temp\SomeProgram.exe";
            someProgram.Start();                  
            streamParamater.CopyTo(someProgram.StandardInput.BaseStream);
            someProgram.WaitForExit();
        }
        catch
        {
            // Error Logging
        }
        finally
        {
            if (someProgram != null)
            {
                someProgram.Dispose();
            }
            streamParamater.Dispose();
        }

Solution

  • The readers / writers and their base streams are not disposed by calling Close() or Dispose() on the Process instance.

    The Process.Close() method just sets the references to null so that they can be collected by GC once there are not other references left.

    There is also this comment in the source code of Process.Close():

    //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.
    

    So, you have to call Dispose() on the readers / writers if you want to make sure that the resources are freed as soon as possible.