Correct way to handle standard error and output from a program when spawned via Process class from C#?

徘徊边缘 提交于 2019-12-01 04:21:05

Your example code could cause a deadlock situtation where there was something written to the StandardOutput and not to StandardError. The very next example from the documentation you linked states as much.

Essentially, what I would recommend, is using the async reads on both streams to fill a buffer as the Streams are written to, and then call WaitForExit.

The problem arises because the child process writes its standard output and standard error into a pair of pipes, which are given a finite buffer by the OS. If the parent is not actively reading both of them then they're liable to fill up. When a pipe fills up, any subsequent writes to it are blocked.

In your example you're reading all of StandardError then all of StandardOutput. This works OK if the child process only writes a little bit of data to StandardError and/or StandardOutput. It's a problem if the child process wants to write a lot of data to StandardOutput. While the parent process is waiting to consume data from StandardError, the child process is busy filling up the StandardOutput buffer.

The safest way is to read from standard in and standard error concurrently. There's a few ways to do this:

  • Spawn separate threads and call ReadToEnd on each
  • Use BeginRead and EndRead on one thread
  • Add handlers on the Process.ErrorDataReceived and Process.OutputDataReceived events, then call Process.BeginErrorReadLine and Process.BeginOutputReadLine.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!