【问题标题】:C# Show output of Process in real time [duplicate]C#实时显示Process的输出[重复]
【发布时间】:2013-07-10 20:04:42
【问题描述】:

在 C# 中,我正在启动一个需要 2 到 3 小时才能完成的第 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);
}

【问题讨论】:

  • @Xeano 不完全相同的问题,但是是的,非常相似。
  • 这很正常,当你重定向它的输出时,进程会切换到缓冲输出。如果它没有吐出很多文本,那么该缓冲区就不会填满足以导致它被刷新。如果您无法修复程序的代码,您将无能为力。

标签: c#


【解决方案1】:

与我之前回答的问题类似,甚至可能是重复的。 见: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(),因为这会使您的程序挂起,直到进程完成。

【讨论】:

  • 上一个问题是什么?提供链接。如果这只是对该答案的反刍,那么您的回复应该是评论,而不是答案。
  • 感谢@JimMischel 的建议,我将在我的答案中添加一个链接。抱歉,如果我的回答不合适,我仍然经常对何时标记答案以及何时回答感到困惑。
【解决方案2】:

线

process.WaitForExit();

将导致当前程序等待给定进程完成。这肯定不是你想要的。您可能想要启动该过程,让它异步运行,然后让它告诉您何时完成。为此,您需要使用 process.Exited 事件。

【讨论】:

  • 当我删除 process.WaitForExit();控制台在后台运行进程然后关闭,它仍然没有显示实时输出。我是否允许来自“OutputHandler”方法的字符串?
猜你喜欢
  • 2021-12-27
  • 2012-02-07
  • 2016-02-24
  • 2011-12-17
  • 1970-01-01
  • 1970-01-01
  • 2011-08-01
  • 1970-01-01
相关资源
最近更新 更多