Getting stdout from console app asyncronously without waiting for console to exit

坚强是说给别人听的谎言 提交于 2019-12-12 23:28:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!