pConsole.StartInfo.RedirectStandardOutput和pConsole.Exited事件(C#) [英] pConsole.StartInfo.RedirectStandardOutput and pConsole.Exited event (c#)

查看:302
本文介绍了pConsole.StartInfo.RedirectStandardOutput和pConsole.Exited事件(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个执行(在新的进程)控制台应用程序的GUI应用程序和解析输出。重定向输出I pConsole.StartInfo.RedirectStandardOutput设置为true。我也赞同事件pConsole.Exited。

I have a GUI application that executes (in a new process) "console" applications and parse the output. To redirect the Output i set the pConsole.StartInfo.RedirectStandardOutput to true. I also subscribes to the event pConsole.Exited.

我看到的问题是,我必须使用Thread.sleep()方法中已退出事件处理程序,以获得最后的数据

The problem I see is that I have to use Thread.Sleep() in the Exited event handler to get the last data.

我已退出事件处理程序是这样的:

My Exited event handler looks like this:

Thread.Sleep(100); // Wait for additional data (if any).
pConsole.OutputDataReceived -= new System.Diagnostics.DataReceivedEventHandler(this.localTerminal_DataAvailableEvent);
int exit = pConsole.ExitCode;
pConsole.Dispose();
pConsole = null;



似乎已退出事件我最后pConsole_DataAvailableEvent之前执行。任何人都知道如何/为什么发生这种情况?

It seems that the Exited event executes before my last pConsole_DataAvailableEvent. Anyone knows how/why this is happening?

我也使用互斥/锁,以确保我才开始执行我的下一个控制台应用程序,我已退出事件就结束了。

I also use a mutex/lock to make sure my Exited event is finished before I start execute my next console application.

推荐答案

问题是几乎可以肯定的输出缓冲:进程退出,引发你的Exited事件,但一些输出数据仍然在缓冲区中。您的黑客可能会在某些情况下工作,但其他方法可能会更强劲。试想一下:

The problem is almost certainly output buffering: the process exits, triggering your Exited event, but some output data is still in the buffer. Your hack will probably work in some cases, but other approaches may be more robust. Consider:

1)消除已退出事件处理程序,而选中Process.HasExited在OutputDataReceived处理程序

1) Eliminating the Exited event handler, and instead check Process.HasExited in the OutputDataReceived handler.

2)不要使用OutputDataReceived处理程序,而只是对Process.StandardOutput流调用read()。做后处理净化后流被关闭。

2) Don't use the OutputDataReceived handler, but simply have a call Read() on the Process.StandardOutput stream. Do the post-process cleanup once the stream is closed.

这篇关于pConsole.StartInfo.RedirectStandardOutput和pConsole.Exited事件(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆