diff --git a/test/TestUtilities/Test.Utility/CommandRunner.cs b/test/TestUtilities/Test.Utility/CommandRunner.cs index 4b7dc6cee61..add0e54cc87 100644 --- a/test/TestUtilities/Test.Utility/CommandRunner.cs +++ b/test/TestUtilities/Test.Utility/CommandRunner.cs @@ -22,7 +22,6 @@ public static CommandRunnerResult Run( bool waitForExit, int timeOutInMilliseconds = 60000, Action inputAction = null, - bool shareProcessObject = false, IDictionary environmentVariables = null) { var psi = new ProcessStartInfo(Path.GetFullPath(process), arguments) @@ -60,27 +59,33 @@ public static CommandRunnerResult Run( Process p = null; - try + using (p = new Process()) { - p = new Process(); + p.OutputDataReceived += OutputHandler; + p.ErrorDataReceived += ErrorHandler; p.StartInfo = psi; p.Start(); - var outputTask = ConsumeStreamReaderAsync(p.StandardOutput, output); - var errorTask = ConsumeStreamReaderAsync(p.StandardError, errors); - inputAction?.Invoke(p.StandardInput); + p.BeginOutputReadLine(); + p.BeginErrorReadLine(); + if (waitForExit) { -#if DEBUG - var processExited = true; +#if DEBUG p.WaitForExit(); + var processExited = true; #else var processExited = p.WaitForExit(timeOutInMilliseconds); #endif - if (!processExited) + if (processExited) + { + p.WaitForExit(); + exitCode = p.ExitCode; + } + else { Kill(p); WaitForExit(p); @@ -89,34 +94,25 @@ public static CommandRunnerResult Run( throw new TimeoutException($"{processName} timed out: " + psi.Arguments); } - - if (processExited) - { - Task.WaitAll(outputTask, errorTask); - exitCode = p.ExitCode; - } } + + p.CancelOutputRead(); + p.CancelErrorRead(); } - finally + + void OutputHandler(object sendingProcess, DataReceivedEventArgs e) { - if (!shareProcessObject) - { - p.Dispose(); - } + if (!string.IsNullOrEmpty(e.Data)) + output.AppendLine(e.Data); } - return new CommandRunnerResult(p, exitCode, output.ToString(), errors.ToString()); - } - - private static async Task ConsumeStreamReaderAsync(StreamReader reader, StringBuilder lines) - { - await Task.Yield(); - - string line; - while ((line = await reader.ReadLineAsync()) != null) + void ErrorHandler(object sendingProcess, DataReceivedEventArgs e) { - lines.AppendLine(line); + if (!string.IsNullOrEmpty(e.Data)) + errors.AppendLine(e.Data); } + + return new CommandRunnerResult(p, exitCode, output.ToString(), errors.ToString()); } private static void Kill(Process process)