[英]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): 考虑这个例子C#代码(不相关的部分遗漏):
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 . 现在,我想通知一个监听器,在没有更多的输出(stdout / stderr)从它读取之后 ,该进程已经完成。 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? 在确定进程是否真正完成之前,我如何在
ExitHandler
方法中确保OutputHandler
和ErrorHandler
处理所有剩余的stdout / stderr?
There is an interlock when you explicitly use Process.WaitForExit(-1). 显式使用Process.WaitForExit(-1)时有一个互锁。 It won't return until the asynchronous readers for stdout and stderr have indicated end-of-file status.
在stdout和stderr的异步读取器指示文件结束状态之前,它不会返回。 Call it in your Exited event handler.
在您的退出事件处理程序中调用它。 You must use a timeout of -1 or this won't work.
您必须使用-1的超时,否则将无效。 Or just WaitForExit().
或者只是WaitForExit()。 Which is fine, you know it already exited.
哪个好,你知道它已经退出了。
The Exited
event is called when the process aborts or terminates. 当进程中止或终止时,将调用
Exited
事件。 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.
然后,组件可以使用它对进程具有的句柄来访问仍驻留在操作系统内存中的关联进程信息(例如ExitTime属性)。
Because the associated process has exited, the Handle property of the component no longer points to an existing process resource.
由于关联的进程已退出,因此组件的Handle属性不再指向现有的进程资源。 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.
系统知道Process组件尚未释放的退出进程的句柄,因此它将ExitTime和Handle属性信息保留在内存中,直到Process组件专门释放资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.