ChildProcessStateBagForConsole.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System.Threading;
  2. namespace SinMaiLauncher.ChildProcessHolder;
  3. internal class ChildProcessStateBagForConsole(ChildProcessKind kind, IProcessStartInfo startInfo) : ChildProcessStateBag(kind, startInfo)
  4. {
  5. public nint? HWndConsole { get; private set; }
  6. protected override async Task<bool> CheckReadyAsync()
  7. {
  8. if (Pid.HasValue == false) return false;
  9. const int timeoutSecond = 5;
  10. var startTime = DateTime.Now;
  11. while (IsAlive && DateTime.Now - startTime < TimeSpan.FromSeconds(timeoutSecond))
  12. {
  13. var h = Program.GetConsoleWindow(Pid.Value);
  14. if (h == -1)
  15. {
  16. await Task.Delay(100);
  17. }
  18. else
  19. {
  20. HWndConsole = h;
  21. break;
  22. }
  23. }
  24. Status = ChildProcessStatus.WaitingReady;
  25. return HWndConsole != null;
  26. }
  27. public override async Task StopAsync(TimeSpan timeout)
  28. {
  29. Status = ChildProcessStatus.Stopping;
  30. if (IsAlive && Pid.HasValue) Program.SendCtrlC(Pid.Value);
  31. await Task.WhenAny(WaitForExitAsync(), Task.Delay(timeout));
  32. await base.StopAsync(timeout);
  33. HWndConsole = null;
  34. }
  35. }