From 2d811e8f582c132ecb580f2ee74518e2a3571e99 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: Fri, 26 Jun 2026 08:58:33 +0800
Subject: [PATCH] ProgressObserver
---
Shared/General/Progress.cs | 29 ++++++++++++++++++++++++++++-
Tests/General/ProgressTest.cs | 22 ++++++++++++++++++++++
2 files changed, 50 insertions(+), 1 deletion(-)
diff --git a/Shared/General/Progress.cs b/Shared/General/Progress.cs
index 75b66aa..ad821bc 100644
--- a/Shared/General/Progress.cs
+++ b/Shared/General/Progress.cs
@@ -54,7 +54,7 @@ public class ProgressProvider {
private readonly List<(double percentage, ProgressProvider sub)> childrens = [];
///
- /// 拆分一个子项:当该子项完成时,当前进度将增至 。
+ /// 拆分一个子项:当该子项完成时,进度将从当前值增加至 。
///
public ProgressProvider SplitTo(double value) {
lock (this) return SplitBy(value - progressSum).First();
@@ -117,3 +117,30 @@ public class ProgressProvider {
}
}
+
+///
+/// 监听进度变化,并将观测到的进度节流后传给更新方法。
+///
+public class ProgressObserver : IDisposable {
+ private readonly ProgressProvider provider;
+ private readonly RateLimitedAction updateAction;
+
+ public ProgressObserver(ProgressProvider provider, Action updateAction, double minimalIntervalMs = 70) {
+ this.provider = provider;
+ this.updateAction = Throttler.Throttle(() => updateAction(provider.Observe()),
+ TimeSpan.FromMilliseconds(minimalIntervalMs), leading: true, trailing: true);
+ provider.ProgressChanged += OnProgressChanged;
+ }
+
+ private void OnProgressChanged() {
+ if (!disposed) updateAction.Invoke();
+ }
+
+ private bool disposed = false;
+ public void Dispose() {
+ if (disposed) return;
+ disposed = true;
+ provider.ProgressChanged -= OnProgressChanged;
+ updateAction.Dispose();
+ }
+}
diff --git a/Tests/General/ProgressTest.cs b/Tests/General/ProgressTest.cs
index f8090a5..4167596 100644
--- a/Tests/General/ProgressTest.cs
+++ b/Tests/General/ProgressTest.cs
@@ -43,4 +43,26 @@ public class ProgressTest : TestBase {
await Assert.That(Math.Abs(progress.Observe() - 2.0 / 3) < 0.000001).IsTrue();
}
+ [Test]
+ public async Task ProgressObserver_监听进度变化并更新UI() {
+ var progress = new ProgressProvider();
+ int updateCount = 0;
+ double updatedProgress = 0;
+
+ using (var observer = new ProgressObserver(progress, value => {
+ updateCount++;
+ updatedProgress = value;
+ }, TimeSpan.FromHours(1))) {
+ progress.Set(0.25);
+
+ await Assert.That(updateCount).IsEqualTo(1);
+ await Assert.That(updatedProgress).IsEqualTo(0.25);
+ }
+
+ progress.Set(0.5);
+ await Task.Delay(50);
+
+ await Assert.That(updateCount).IsEqualTo(1);
+ }
+
}