C # Show process output in real time

In C #, I run a third-party application that takes 2 to 3 hours. I need the output of a process to write to the console in real time. I did research on BeginOutputReadLine() and RedirectStandardOutput from the Microsoft website, but my code still does not work.

Currently, my code only shows the result when the process is complete. I don’t know where everything went 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); } 
+6
source share
2 answers

Line

 process.WaitForExit(); 

make the current program wait for the completion of this process. This is definitely not what you want; you probably want to start the process, let it start asynchronously, and then let it tell you when it finishes. For this you need to use the process.Exited event.

+6
source

As in the previous question, I answered, maybe even a duplicate. See: Swipe a stream in Debug.Write ()

Here is my answer (slightly modified):

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

Then your event handler to retrieve the data.

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

Basically, you just need to execute nix WaitForExit (), as this causes your program to freeze until the process terminates.

+2
source

Source: https://habr.com/ru/post/949157/


All Articles