我尝试使用 StreamReader 从进程读取输出数据,但 StreamReader 会阻塞并且不会返回任何输出。
我的流程如下所示:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.Arguments = args;
startInfo.FileName = filename;
StartInfo.WorkingDirectory = aDirectory;
StartInfo.UseShellExecute = false;
StartInfo.RedirectStandardOutput = true;
Process p = new Process();
p.StartInfo = startInfo;
p.Start();
随后立即调用 StreamReader:
StreamReader strmRead = p.StandardOutput;
char[] output = new char[4096];
while(true){
strmRead.Read(output,0,output.Length);
string outputString = new string(output);
Debug.WriteLine(outputString);
}
代码在调用 Read 方法时挂起。当我手动终止程序时,进程的输出将写入调试控制台。进程输出不使用换行符,因此使用 Process.OutputDataReceived 不起作用。如何从流中获取进程输出而不让它无限期地阻塞?
编辑:鉴于我已经得到的答案,这似乎是进程没有放弃标准输出或没有刷新输出的问题,而不是我的代码有任何问题。如果其他人有任何见解,请随时发表评论。
最佳答案
您正在读取 4096 字节,可能会更少,因此流会阻塞。
此外,还有更有效的方法从流中读取文本。 TextReader
有 ReadLine
方法,请尝试使用该方法。
http://msdn.microsoft.com/en-us/library/system.io.textreader.readline.aspx
顺便说一句,while (true)
???您打算如何退出?
关于c# - 使用 Streamreader.Read block /RedirectStandardOutput,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10839106/