How to use System.Diagnostics.Process correctly

时间:2022-08-29 14:50:18

I’ve seen many a question on * and other places about running a process and capturing it’s output. Using the System.Diagnostics.Process correctly is not easy and most often it’s done wrong.

Some common mistakes with System.Diagnostics.Process:

  1. Not capturing both output streams (error & output)
  2. Not redirecting input can cause applications to hang
  3. Not closing redirected input can cause applications to hang
  4. Not calling BeginOutputReadLine/BeginErrorReadLine when using events
  5. Using OutputDataReceived/ErrorDataReceived without waiting for null
  6. Not checking for null in OutputDataReceived/ErrorDataReceived handlers
  7. Forgetting to set EnableRaisingEvents = true; when using the Exited event
  8. Forgetting ErrorDialog, CreateNoWindow, or UseShellExecute settings
  9. Incorrect handling of StandardOutput or StandardError stream readers

 

So with this said, here are some basic guidelines:

  1. Use the OutputDataReceived/ErrorDataRecieved events NOT the StandardOutput or StandardError. This will save you a lot of headache and needless thread management.
  2. Always capture all output AND input, if you don’t plan to provide input, close the stream immediately.
  3. Your process isn’t done until it exited AND you have read all the data. OutputDataReceived CAN AND WILL be fired after a call to WaitForExit() returns. You will need wait handles for each output stream and set the wait handle once your receive (null) data.

 

Additional Resources: