C#实时显示Process的输出

在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); } 

这条线

 process.WaitForExit(); 

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

类似于我之前回答的问题,甚至可能是重复的。 请参阅: 将流传输到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(),因为这会使您的程序挂起,直到该过程完成。