我阅读了 Process.StandardOutput 的文档,其中有这样的报价:
A deadlock condition can result if the parent process calls p.WaitForExit before p.StandardOutput.ReadToEnd and the child process writes enough text to fill the redirected stream.
所以我想知道。如果我也担心在某些情况下可以填充 StandardError,那么正确的方法是什么?
我是否必须使用循环来交替读取标准输出和错误,以避免填满,或者这个简单的代码是否足够:
string error = proc.StandardError.ReadToEnd();
string output = proc.StandardOutput.ReadToEnd();
bool didFinish = proc.WaitForExit(60000);
在发布了一些答案后进行了编辑
所以这是正确的方法吗?
var output = new StringBuilder();
proc.OutputDataReceived += (s, e) => output.Append(e.Data);
proc.BeginOutputReadLine();
string error = proc.StandardError.ReadToEnd();
bool didFinish = proc.WaitForExit(60000);
然后我仅在过程实际完成时才使用 stringbuilder 内容。
那么这是正确的方法吗?
最佳答案
您的示例代码可能会导致死锁情况,其中向 StandardOutput
写入了一些内容。而不是 StandardError
.您链接的文档中的下一个示例也说明了这一点。
本质上,我建议的是在写入流时使用两个流上的异步读取来填充缓冲区,然后调用 WaitForExit
.
关于.net - 当通过 C# 的 Process 类产生时,处理标准错误和程序输出的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4137346/