Last active
June 14, 2017 22:02
-
-
Save a5ync/296686709cf350357284ba19d8c1c789 to your computer and use it in GitHub Desktop.
Asynchronous awaitable Process.Start()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| namespace Helpers | |
| { | |
| using System; | |
| using System.Collections.Generic; | |
| using System.Diagnostics; | |
| using System.IO; | |
| using System.Threading.Tasks; | |
| public static class ProcessExecutor | |
| { | |
| public static async Task<int> RunProcessAsync(string fileName, string args) | |
| { | |
| using (var process = new Process | |
| { | |
| StartInfo = | |
| { | |
| FileName = fileName, | |
| Arguments = args, | |
| UseShellExecute = false, | |
| CreateNoWindow = true, | |
| RedirectStandardOutput = true, | |
| RedirectStandardError = true | |
| }, | |
| EnableRaisingEvents = true | |
| }) | |
| { | |
| return await RunProcessAsync(process).ConfigureAwait(false); | |
| } | |
| } | |
| private static Task<int> RunProcessAsync(Process process) | |
| { | |
| var tcs = new TaskCompletionSource<int>(); | |
| process.Exited += (s, ea) => tcs.SetResult(process.ExitCode); | |
| process.OutputDataReceived += (s, ea) => | |
| { | |
| if (ea.Data != null) | |
| { | |
| Console.WriteLine(ea.Data); | |
| } | |
| }; | |
| process.ErrorDataReceived += (s, ea) => | |
| { | |
| if (ea.Data != null) | |
| { | |
| Console.WriteLine($"ERR: {ea.Data}"); | |
| } | |
| }; | |
| var started = process.Start(); | |
| if (!started) | |
| { | |
| throw new InvalidOperationException($"Could not start process {process}"); | |
| } | |
| process.BeginOutputReadLine(); | |
| process.BeginErrorReadLine(); | |
| return tcs.Task; | |
| } | |
| private static async Task<int> ExecuteExternalProcess(string executablePath, string arguments) | |
| { | |
| if (!File.Exists(executablePath)) | |
| { | |
| throw new FileNotFoundException($"Could not start process executablePath {executablePath}"); | |
| } | |
| return await RunProcessAsync(executablePath, arguments); | |
| } | |
| public static async Task<int> ExecuteProcess(string executable, List<string> arguments) | |
| { | |
| return await ExecuteProcess(executable, string.Join(" ", arguments)); | |
| } | |
| public static Task<int> ExecuteProcess(string executable, string arguments) | |
| { | |
| return ExecuteExternalProcess(executable, arguments); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment