ProcessExtensions.cs 957 B

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