Problem with StandardOutput stream in asynchronous mode

I have a program that starts command line processes in asynchronous mode using BeginOutputReadLine. My problem is that the .Exited event is fired when some .OutputDataReceived events are still fired. What I do in my .Exited event should happen only after all my .OutputDataReceived events have completed, or I will skip some output.

I looked in the Process class to find out if something could be useful to me, since waiting for the thread to be empty, but all I find is for synchronization mode only. Can any of you help?

Thanx.

+1
source share
1 answer

I had a similar problem: my application is essentially an interface for some cygwin applications, and sometimes the application exits all the data received through the OutputDataReceived event, and I lose data.

My fix / hack is to call WaitUtilEOF on the AsyncStreamReader output before the process object disappears (you need to use reflection, since WaitUtilEOF is in the inner class of the .NET platform). This results in the caller being blocked until all asynchronization data has been cleared through OutputDataReceived. I am not sure if it will directly solve your problem, but it may 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 call it this way:

 WaitUntilAsyncStreamReachesEndOfFile(process, "output"); 

Good luck

+1
source

Source: https://habr.com/ru/post/1442720/


All Articles