C# Show output of Process in real time [duplicate]

2020-03-01 15:37发布

In C# I am starting a 3rd party application that takes 2 - 3 hours to complete. I need the output of the Process to write to the console in real time. I have done research on BeginOutputReadLine() and RedirectStandardOutput from Microsoft's website but my code is still not working.

Currently my code is only showing the output when the process is finished. I don't know where its gone wrong.

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

标签: c#
2条回答
够拽才男人
2楼-- · 2020-03-01 16:14

Similar to a previous question I'd answered, maybe even a duplicate. See: Pipe a stream to Debug.Write()

Here's my answer (modified slightly) from that:

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

Then, your event handler for receiving data.

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

Basically, you just need to nix the WaitForExit(), since that makes your program hang until the process completes.

查看更多
Bombasti
3楼-- · 2020-03-01 16:15

The line

process.WaitForExit();

will cause the current program to wait until the given process finishes. This is most certainly not what you want; you probably want to start the process, let it run asynchronously, and then let it tell you when it finishes. For that, you will want to use the process.Exited event.

查看更多
登录 后发表回答