Problem with StandardOutput stream in async mode
I have a program that launches command line processes in async mode, using BeginOutputReadLine. My problem is that the .Exited event is triggered when there is still some .OutputDataReceived events being triggered. What I 开发者_如何学JAVAdo in my .Exited event must happen only once all my .OutputDataReceived events are done, or I'll be missing some output.
I looked in the Process class to see if anything could be useful to me, as to wait for the stream to be empty, but all I find is for sync mode only. Can any of you help?
Thanx.
I've run into a similar problem: my app's essentially a frontend to some cygwin apps and sometimes the app exits before all of the data's received via the OutputDataReceived event, and I lose data.
My fix / hack is to call WaitUtilEOF on the output AsyncStreamReader before the process object disappears (have to use reflection since WaitUtilEOF is on an .NET framework internal class). This causes the caller to block until all of the async data has been flushed through OutputDataReceived. I'm not sure if it'll directly solve your problem, but it might help...
private static void WaitUntilAsyncStreamReachesEndOfFile(Process process, string field)
{
FieldInfo asyncStreamReaderField = typeof(Process).GetField(field, BindingFlags.NonPublic | BindingFlags.Instance);
object asyncStreamReader = asyncStreamReaderField.GetValue(process);
Type asyncStreamReaderType = asyncStreamReader.GetType();
MethodInfo waitUtilEofMethod = asyncStreamReaderType.GetMethod(@"WaitUtilEOF", BindingFlags.NonPublic | BindingFlags.Instance);
object[] empty = new object[] { };
waitUtilEofMethod.Invoke(asyncStreamReader, empty);
}
And i'm calling it like this:
WaitUntilAsyncStreamReachesEndOfFile(process, "output");
Good luck!
精彩评论