Process.StandardOutput.Read()挂起空缓冲区

时间:2014-02-03 09:51:41

标签: c# process io-redirection

我的目标是能够一次异步读取进程字符的stdout流。我的简化但仍然失败的代码如下。读取读取字符直到所有字符都被读取,但是当它返回另一个字符时它永远不会返回。我正在使用Win 8.1 Pro 64位,VS2013 Ultimate,以及为.NET 4.5构建。

谢谢, 射线

  public static void RunIt()
  {
     Process process = new Process();
     process.StartInfo.FileName = "D:\\temp\\C1A7E1.exe";
     process.StartInfo.UseShellExecute = false;
     process.StartInfo.RedirectStandardOutput = true;
     process.StartInfo.RedirectStandardError = true;
     process.StartInfo.RedirectStandardInput = true;
     process.StartInfo.CreateNoWindow = true;
     process.Start();

     string textString = string.Empty;
     for (; ; )
     {
        int outputCharInt;
        if ((outputCharInt = process.StandardOutput.Read()) != -1)
           textString += (char)outputCharInt;
        else
           Thread.Sleep(1000);
     }
  }

1 个答案:

答案 0 :(得分:1)

如果您想异步读取标准输出,则必须处理Prcess.OutputDataReceived事件并使用Process.BeginOutputReadLine()方法,如下所示:

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo("process file");
startInfo.RedirectStandardOutput = true;
process.StartInfo = startInfo;
process.OutputDataReceived += process_OutputDataReceived;
...
process.Start();
process.BeginOutputReadLine(); // Starts the asynchronous read

private void process_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
{
   if (!string.IsNullOrEmpty(e.Data))
   {
     ...
   }
}

作为参考,请参阅:MSDN