From be802ede2ec4a8aaf1818a06cbe61484f1bef3f5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E9=BE=99=E8=85=BE=E7=8C=AB=E8=B7=83?= <1043137532@qq.com>
Date: Sun, 28 Jun 2026 08:00:39 +0800
Subject: [PATCH] =?UTF-8?q?TaskUtils=20=E7=9A=84=E8=BF=9B=E5=BA=A6?=
=?UTF-8?q?=E6=94=AF=E6=8C=81?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
Shared/General/Progress.cs | 2 +
Shared/Utils/TaskUtils.cs | 105 +++++++++++++++++++++++++----------
Tests/Utils/TaskUtilsTest.cs | 45 +++++++++++++++
3 files changed, 123 insertions(+), 29 deletions(-)
create mode 100644 Tests/Utils/TaskUtilsTest.cs
diff --git a/Shared/General/Progress.cs b/Shared/General/Progress.cs
index c767dc9..036bd77 100644
--- a/Shared/General/Progress.cs
+++ b/Shared/General/Progress.cs
@@ -16,6 +16,8 @@ public class ProgressProvider {
private (double actual, double skiped, double splited) progressParts = (0, 0, 0);
private double progressSum => progressParts.actual + progressParts.skiped + progressParts.splited;
+ public bool Finished => progressParts.actual + progressParts.skiped > 0.9999999;
+
private bool _Set(double value, bool skiped) {
value = value.Clamp(0, 1);
double delta = value - progressSum;
diff --git a/Shared/Utils/TaskUtils.cs b/Shared/Utils/TaskUtils.cs
index 203ad29..e2abdab 100644
--- a/Shared/Utils/TaskUtils.cs
+++ b/Shared/Utils/TaskUtils.cs
@@ -3,6 +3,82 @@ using System.Diagnostics;
namespace MeloongCore;
public static class TaskUtils {
+ ///
+ /// 并行执行所有任务。
+ ///
+ public static Task WhenAll(IEnumerable> tasks, ProgressProvider? progress = null) {
+ var taskList = tasks.ToList();
+ if (!taskList.Any()) {
+ progress?.Skip();
+ return Task.CompletedTask;
+ }
+ // 实际分割
+ var progressEach = 1d / taskList.Count;
+ return Task.WhenAll(taskList.Select(async (task, index) => {
+ var cp = progress?.SplitBy(progressEach)[0];
+ await task(cp).ConfigureAwait(false);
+ cp?.Finish();
+ }));
+ }
+ ///
+ /// 并行执行所有任务并返回结果。
+ ///
+ public static Task WhenAll(IEnumerable>> tasks, ProgressProvider? progress = null) {
+ var taskList = tasks.ToList();
+ if (!taskList.Any()) {
+ progress?.Skip();
+ return Task.FromResult(Array.Empty());
+ }
+ // 实际分割
+ var progressEach = 1d / taskList.Count;
+ return Task.WhenAll(taskList.Select(async (task, index) => {
+ var cp = progress?.SplitBy(progressEach)[0];
+ var result = await task(cp).ConfigureAwait(false);
+ cp?.Finish();
+ return result;
+ }));
+ }
+ ///
+ /// 并行执行所有任务。
+ ///
+ public static Task WhenAll(IEnumerable tasks, ProgressProvider? progress = null)
+ => WhenAll(tasks.Select(task => new Func(_ => task)), progress);
+ ///
+ /// 并行执行所有任务并返回结果。
+ ///
+ public static Task WhenAll(IEnumerable> tasks, ProgressProvider? progress = null)
+ => WhenAll(tasks.Select(task => new Func>(_ => task)), progress);
+
+ public static void ForEach(IEnumerable source, Action body)
+ => Parallel.ForEach(source, body);
+ public static async Task ForEachAsync(IEnumerable source, int maxDegreeOfParallelism, Func body,
+ CancellationToken cancellationToken = default, ProgressProvider? progress = null) {
+ using var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ var token = linkedCancellationTokenSource.Token;
+ var enumeratorLock = new object();
+ using var enumerator = source.GetEnumerator();
+ async Task WorkerAsync(ProgressProvider? cp) {
+ try {
+ while (true) {
+ T item;
+ lock (enumeratorLock) {
+ token.ThrowIfCancellationRequested();
+ if (!enumerator.MoveNext()) return;
+ item = enumerator.Current;
+ }
+ await body(item, cp).ConfigureAwait(false);
+ }
+ } catch {
+ try {
+ linkedCancellationTokenSource.Cancel(); // 让尚未开始的 worker 尽快停止
+ } catch {
+ }
+ throw;
+ }
+ }
+ await TaskUtils.WhenAll(Enumerable.Repeat(WorkerAsync, maxDegreeOfParallelism), progress).ConfigureAwait(false);
+ }
+
///
/// 静默运行程序并等待其结束,返回其输出和退出码。
/// 支持 notepad、git 等命令。
@@ -46,33 +122,4 @@ public static class TaskUtils {
return (await outputTask + await errorTask, program.ExitCode);
}
- public static void ForEach(IEnumerable source, Action body)
- => Parallel.ForEach(source, body);
- public static async Task ForEachAsync(IEnumerable source, int maxDegreeOfParallelism, Func body, CancellationToken cancellationToken = default) {
- using var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
- var token = linkedCancellationTokenSource.Token;
- var enumeratorLock = new object();
- using var enumerator = source.GetEnumerator();
- async Task WorkerAsync() {
- try {
- while (true) {
- T item;
- lock (enumeratorLock) {
- token.ThrowIfCancellationRequested();
- if (!enumerator.MoveNext()) return;
- item = enumerator.Current;
- }
- await body(item, token).ConfigureAwait(false);
- }
- } catch {
- try {
- linkedCancellationTokenSource.Cancel(); // 让尚未开始的 worker 尽快停止
- } catch {
- }
- throw;
- }
- }
- await Task.WhenAll([.. Enumerable.Range(0, maxDegreeOfParallelism).Select(_ => Task.Run(WorkerAsync))]).ConfigureAwait(false);
- }
-
}
diff --git a/Tests/Utils/TaskUtilsTest.cs b/Tests/Utils/TaskUtilsTest.cs
new file mode 100644
index 0000000..d3efc6f
--- /dev/null
+++ b/Tests/Utils/TaskUtilsTest.cs
@@ -0,0 +1,45 @@
+namespace MeloongCore.Tests;
+
+public class TaskUtilsTest : TestBase {
+
+ [Test]
+ public async Task WhenAll_汇总等权子进度并保持结果顺序() {
+ var progress = new ProgressProvider();
+ var continueSecond = new TaskCompletionSource