问题描述
我阅读了 Process.StandardOutput 的文档,其中有这样的引用:
I read the documentation for Process.StandardOutput, which has this quote:
如果父进程在 p.StandardOutput.ReadToEnd 之前调用 p.WaitForExit 并且子进程写入足够的文本来填充重定向的流,则可能导致死锁情况.
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,那么正确的方法是什么?
So I'm wondering. What is the correct way to do this if I'm also afraid that StandardError could be filled in some scenarios?
我是否必须使用循环来交替读取标准输出和错误,以避免填满,或者这个简单的代码是否足够:
Do I have to use a loop to alternate reading from standard output and error, to avoid either filling up, or is this simple code enough:
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);
然后,我仅在过程实际完成时才使用字符串生成器内容.
And then I use the stringbuilder content only if the process actually finished.
那是正确的方法吗?
推荐答案
您的示例代码可能会导致死锁情况,其中有一些内容写入 StandardOutput
而不是 StandardError
.您链接的文档中的下一个示例说明了这一点.
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.
基本上,我建议的是,在写入流时使用两个流上的异步读取来填充缓冲区,然后调用 WaitForExit
.
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
.
这篇关于通过 C# 的 Process 类生成时,处理标准错误和程序输出的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!