TaskUtils.cs 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System.Diagnostics;
  2. namespace MeloongCore;
  3. public static class TaskUtils {
  4. /// <summary>
  5. /// 并行执行所有任务。
  6. /// </summary>
  7. public static Task WhenAll(IEnumerable<Func<ProgressProvider?, Task>> tasks, ProgressProvider? progress = null) {
  8. var taskList = tasks.ToList();
  9. if (!taskList.Any()) {
  10. progress?.Skip();
  11. return Task.CompletedTask;
  12. }
  13. // 实际分割
  14. var progressEach = 1d / taskList.Count;
  15. return Task.WhenAll(taskList.Select(async (task, _) => {
  16. var cp = progress?.SplitBy(progressEach)[0];
  17. await task(cp).NoCapture();
  18. cp?.Finish();
  19. }));
  20. }
  21. /// <summary>
  22. /// 并行执行所有任务并返回结果。
  23. /// </summary>
  24. public static Task<TResult[]> WhenAll<TResult>(IEnumerable<Func<ProgressProvider?, Task<TResult>>> tasks, ProgressProvider? progress = null) {
  25. var taskList = tasks.ToList();
  26. if (!taskList.Any()) {
  27. progress?.Skip();
  28. return Task.FromResult(Array.Empty<TResult>());
  29. }
  30. // 实际分割
  31. var progressEach = 1d / taskList.Count;
  32. return Task.WhenAll(taskList.Select(async (task, _) => {
  33. var cp = progress?.SplitBy(progressEach)[0];
  34. var result = await task(cp).NoCapture();
  35. cp?.Finish();
  36. return result;
  37. }));
  38. }
  39. /// <summary>
  40. /// 并行执行所有任务。
  41. /// </summary>
  42. public static Task WhenAll(IEnumerable<Task> tasks, ProgressProvider? progress = null)
  43. => WhenAll(tasks.Select(task => new Func<ProgressProvider?, Task>(_ => task)), progress);
  44. /// <summary>
  45. /// 并行执行所有任务并返回结果。
  46. /// </summary>
  47. public static Task<TResult[]> WhenAll<TResult>(IEnumerable<Task<TResult>> tasks, ProgressProvider? progress = null)
  48. => WhenAll(tasks.Select(task => new Func<ProgressProvider?, Task<TResult>>(_ => task)), progress);
  49. public static void ForEach<T>(IEnumerable<T> source, Action<T> body)
  50. => Parallel.ForEach(source, body);
  51. /// <summary>
  52. /// 静默运行程序并等待其结束,返回其输出和退出码。
  53. /// 支持 notepad、git 等命令。
  54. /// 超时或启动失败会抛出异常。
  55. /// </summary>
  56. public static async Task<(string Output, int ExitCode)> RunProgramAsync(string file, string arguments = "", int? timeoutMs = null, Encoding? encoding = null, CancellationToken cancellationToken = default) {
  57. cancellationToken.ThrowIfCancellationRequested();
  58. var info = new ProcessStartInfo {
  59. Arguments = arguments,
  60. FileName = PathUtils.ToShortPath(file),
  61. UseShellExecute = false,
  62. CreateNoWindow = true,
  63. RedirectStandardOutput = true, StandardOutputEncoding = encoding,
  64. RedirectStandardError = true, StandardErrorEncoding = encoding
  65. };
  66. using var program = new Process();
  67. program.StartInfo = info;
  68. program.EnableRaisingEvents = true;
  69. if (!program.Start()) throw new InvalidOperationException($"运行程序时出现意外错误:{file} {arguments}");
  70. bool hasTimeout = timeoutMs is > 0;
  71. Logger.Info($"运行程序,并返回其输出:{file} {arguments}{(hasTimeout ? $",最长可等待 {timeoutMs}ms" : "")}");
  72. // 输出和错误流
  73. var outputTask = program.StandardOutput.ReadToEndAsync();
  74. var errorTask = program.StandardError.ReadToEndAsync();
  75. var completionSource = new TaskCompletionSource<object?>(TaskCreationOptions.RunContinuationsAsynchronously);
  76. program.Exited += (_, _) => completionSource.TrySetResult(null);
  77. if (program.HasExited) completionSource.TrySetResult(null);
  78. var task = completionSource.Task;
  79. var timeoutTask = Task.Delay(hasTimeout ? timeoutMs!.Value : Timeout.Infinite);
  80. var cancelTask = Task.Delay(Timeout.Infinite, cancellationToken);
  81. Logger.Trace($"等待程序 {program.Id} 完成");
  82. var completedTask = await Task.WhenAny(task, timeoutTask, cancelTask).NoCapture();
  83. if (completedTask != task) {
  84. try {
  85. if (!program.HasExited) program.Kill();
  86. } catch (InvalidOperationException) { // 进程已退出,无需处理
  87. }
  88. if (completedTask == cancelTask) throw new OperationCanceledException(cancellationToken);
  89. throw new TimeoutException($"运行程序超时:{file} {arguments}");
  90. }
  91. return (await outputTask.NoCapture() + await errorTask.NoCapture(), program.ExitCode);
  92. }
  93. }