| 1 | using System; |
| 2 | using System.Diagnostics; |
| 3 | using System.Threading; |
| 4 | using System.Threading.Tasks; |
| 5 | |
| 6 | namespace GodotTools.Core |
| 7 | { |
| 8 | public static class ProcessExtensions |
| 9 | { |
| 10 | public static async Task WaitForExitAsync(this Process process, CancellationToken cancellationToken = default) |
| 11 | { |
| 12 | var tcs = new TaskCompletionSource<bool>(); |
| 13 | |
| 14 | void ProcessExited(object? sender, EventArgs e) |
| 15 | { |
| 16 | tcs.TrySetResult(true); |
| 17 | } |
| 18 | |
| 19 | process.EnableRaisingEvents = true; |
| 20 | process.Exited += ProcessExited; |
| 21 | |
| 22 | try |
| 23 | { |
| 24 | if (process.HasExited) |
| 25 | return; |
| 26 | |
| 27 | using (cancellationToken.Register(() => tcs.TrySetCanceled())) |
| 28 | { |
| 29 | await tcs.Task; |
| 30 | } |
| 31 | } |
| 32 | finally |
| 33 | { |
| 34 | process.Exited -= ProcessExited; |
| 35 | } |
| 36 | } |
| 37 | } |
| 38 | } |