/// <summary> /// Start a program and get notified of lines in realtime through <paramref name="lineHandler"/> unlike <see cref="Start(string,string[])"/> /// This won't capture all lines on the returned object and won't default to writing to the Console. /// </summary> /// <param name="timeout">The maximum runtime of the started program</param> /// <param name="started">A callback when the process is ready to receive standard in writes</param> /// <param name="lineHandler"> /// An implementation of <see cref="IConsoleLineHandler"/> that receives every line as <see cref="LineOut"/> or the <see cref="Exception"/> that occurs while running /// </param> /// <returns>The exit code and whether the process completed</returns> public static ProcessResult StartRedirected(StartArguments arguments, TimeSpan timeout, StartedHandler started, IConsoleLineHandler lineHandler = null) { using (var composite = new CompositeDisposable()) { var process = new ObservableProcess(arguments); if (started != null) { process.ProcessStarted += started; } Exception seenException = null; composite.Add(process); composite.Add(process.SubscribeLines( l => lineHandler?.Handle(l), e => { seenException = e; lineHandler?.Handle(e); }) ); var completed = process.WaitForCompletion(timeout); if (seenException != null) { ExceptionDispatchInfo.Capture(seenException).Throw(); } return(new ProcessResult(completed, process.ExitCode)); } }
/// <summary> Starts a programs and captures the output while writing to the console at the same time </summary> /// <param name="timeout">The maximum runtime of the started program</param> /// <param name="started">A callback when the process is ready to receive standard in writes</param> /// <param name="consoleOutWriter"> /// An implementation of <see cref="IConsoleOutWriter"/> that takes care of writing to the console /// <para>defaults to <see cref="ConsoleOutColorWriter"/> which writes standard error messages in red</para> /// </param> /// <returns>An object holding a list of console out lines, the exit code and whether the process completed</returns> public static ProcessResult Start(StartArguments arguments, TimeSpan timeout, IConsoleOutWriter consoleOutWriter, StartedHandler started) { using (var composite = new CompositeDisposable()) { var process = new ObservableProcess(arguments); if (started != null) { process.ProcessStarted += started; } Exception seenException = null; var consoleOut = new List <LineOut>(); composite.Add(process); if (consoleOutWriter == null) { composite.Add(process.SubscribeLines(consoleOut.Add, e => seenException = e)); } else { composite.Add(process.SubscribeLinesAndCharacters( consoleOut.Add, e => seenException = e, consoleOutWriter.Write, consoleOutWriter.Write ) ); } var completed = process.WaitForCompletion(timeout); if (seenException != null) { ExceptionDispatchInfo.Capture(seenException).Throw(); } return(new ProcessResult(completed, consoleOut, process.ExitCode)); } }