c# - 使用 Streamreader.Read block /RedirectStandardOutput

标签 c# process

我尝试使用 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 字节,可能会更少,因此流会阻塞。

此外,还有更有效的方法从流中读取文本。 TextReaderReadLine 方法,请尝试使用该方法。

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/

相关文章:

c++ - 进程终止 C++

c# - 将 ByteArray 转换为 String 以在 TextBox c# 中使用

c# - 空安全字符串

c - 多个 fork()。 main怎么知道pid的?

java - System.Diagnostics.Process 参数中路径中的空格问题

c# - 从 Process.StandardOutput 捕获二进制输出

在xeyes(终端)中永久改变中心颜色的c代码

c# - 如何生成长指南?

c# - 以编程方式将新行添加到 DataTable C#

c# - 在 C# 应用程序中更改 "(default)"ResX 语言