简体   繁体   中英

Using System.Diagnostics.Process asynchronously, how should I ensure that I've received the last output before determining it has exited?

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.

The Exited event is called when the process aborts or terminates. There should therefore never be a situation whereby there is still data to read.

When the operating system shuts down a process, any process component that is waiting for an exit is notified. The component can then access the associated process information that is still resident in the operating system memory (such as ExitTime property) by using the handle that it has to the process.

Because the associated process has exited, the Handle property of the component no longer points to an existing process resource. Instead, it can be used only to access the operating system's information about the process resource. The system is aware of handles to exited processes that have not been released by Process components, so it keeps the ExitTime and Handle property information in memory until the Process component specifically frees the resources.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM