C#实时显示Process的输出

时间:2013-07-10 20:04:42

标签: c#

在C#中,我正在启动第三方应用程序,需要2-3个小时才能完成。我需要Process的输出实时写入控制台。我已经对微软网站上的BeginOutputReadLine()RedirectStandardOutput进行了研究,但我的代码仍无效。

目前我的代码仅在流程结束时显示输出。我不知道它出了什么问题。

static void Main(string[] args)
{
  Process process;
  process = new Process();
  process.StartInfo.FileName = "C:\\ffmbc\\ffmbc.exe";
  process.StartInfo.Arguments = "-i \\\\dssp-isi-t\\TMD\\B002C010_130520_R2R7.2398v5.mxf -an -vcodec libx264 -level 4.1 -preset veryslow -tune film -x264opts bluray-compat=1:weightp=0:bframes=3:nal-hrd=vbr:vbv-maxrate=40000:vbv-bufsize=30000:keyint=24:b-pyramid=strict:slices=4:aud=1:colorprim=bt709:transfer=bt709:colormatrix=bt709:sar=1/1:ref=4 -b 30M -bt 30M -threads 0 -pass 1 -y \\\\dss-isi-t\\MTPO_Transfer\\dbay\\B002C010_130520_R2R7.2398v5.mxf.h264";
  process.StartInfo.UseShellExecute = false;
  process.StartInfo.CreateNoWindow = true;
  process.StartInfo.RedirectStandardOutput = true;
  process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
  process.StartInfo.RedirectStandardInput = true;
  process.Start();
  process.BeginOutputReadLine();
  process.WaitForExit();
  process.Close();
}

private static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
  string line;
  line = (outLine.Data.ToString());
  Console.WriteLine(line);
}

2 个答案:

答案 0 :(得分:6)

该行

process.WaitForExit();

将导致当前程序等到给定进程完成。这肯定不是你想要的;你可能想要启动它,让它以异步方式运行,然后让它告诉你它什么时候结束。为此,您需要使用process.Exited事件。

答案 1 :(得分:5)

与我之前回答的问题相似,甚至可能是重复的。 请参阅:Pipe a stream to Debug.Write()

这是我的答案(略有修改):

process.StartInfo.UseShellExecute = false; 
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += p_OutputDataReceived;
process.Start();
process.BeginOutputReadLine();

然后,您的事件处理程序用于接收数据。

void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    Console.Write(e.Data);
}

基本上,您只需要修改WaitForExit(),因为这会使您的程序挂起,直到该过程完成。