问题
I have an issue with getting some console standard output from a small long running console app spawned by my application.
My app starts the console app and the console app will stay alive listening on a port for the duration of my applications lifetime (or until explicitly killed).
When the console app starts, it outputs a port number that it is listening on, I need to asyncronously grab that port number and use it elsewhere in the app. Problem is, my event handler to get the output data is never called. I am sure there must be something trivial I am forgetting to do.
ProcessStartInfo si = new ProcessStartInfo();
si.FileName = theFileName;
si.Arguments = theargs;
si.UseShellExecute = false;
si.RedirectStandardOutput = true;
si.CreateNoWindow = true;
_process = Process.Start(si);
_process.OutputDataReceived += (sender, args) =>
{
//Parse the args.Data string for the port number.
};
_process.BeginOutputReadLine(); // My handler never gets called.
// I don't want to call _process.WaitForExit() here as this is a long running process.
回答1:
Ok in my particular case the issue was caused by the console app not flushing stdout.
The console app was written in python (then made runnable in windows by py2exe), it required...
sys.stdout.flush()
To be called before we could get any output prior to app exit.
来源:https://stackoverflow.com/questions/5466873/getting-stdout-from-console-app-asyncronously-without-waiting-for-console-to-exi