Consider this example C# code (irrelevant pieces left out):
using System.Diagnostics.Process;
var process = new Process();
var startInfo = process.StartInfo;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
process.EnableRaisingEvents = true;
process.OutputDataReceived += OutputHandler;
process.ErrorDataReceived += ErrorHandler;
process.Exited += ExitHandler;
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
Now, I want to notify a listener that the process is finished after there is no more output (stdout/stderr) to read from it. How do I ensure in my ExitHandler method that all remaining stdout/stderr is processed by OutputHandler and ErrorHandler before determining that the process has truly finished?
There is an interlock when you explicitly use Process.WaitForExit(-1). It won’t return until the asynchronous readers for stdout and stderr have indicated end-of-file status. Call it in your Exited event handler. You must use a timeout of -1 or this won’t work. Or just WaitForExit(). Which is fine, you know it already exited.