RedoableWorker.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. namespace MeloongCore;
  2. public interface IWorker {
  3. /// <summary>在工作线程运行工作负载。</summary>
  4. void Start(CancellationToken cancellationToken = default, ProgressProvider? progressOverride = null);
  5. /// <summary>取消当前运行。</summary>
  6. void Cancel();
  7. /// <summary>若当前正在运行中,等待其完成。若未在运行中,则立即返回。</summary>
  8. /// <returns>若未超时则返回 true。</returns>
  9. bool WaitIfRunning(int millisecondsTimeout = -1, CancellationToken cancellationToken = default);
  10. /// <summary>若当前正在运行中,异步等待其完成。若未在运行中,则立即返回。</summary>
  11. /// <returns>若未超时则返回 true。</returns>
  12. Task<bool> WaitIfRunningAsync(int millisecondsTimeout = -1, CancellationToken cancellationToken = default);
  13. /// <summary>从空闲状态进入运行状态时触发。</summary>
  14. event Action? Started;
  15. /// <summary>运行结束并进入空闲状态时触发。</summary>
  16. event Action? Stopped;
  17. /// <summary>工作负载成功完成时触发。</summary>
  18. public event Action? Succeeded;
  19. /// <summary>工作负载执行失败时触发,参数为发生的异常。</summary>
  20. public event Action<Exception>? Failed;
  21. /// <summary>运行被取消时触发。</summary>
  22. event Action? Canceled;
  23. /// <summary>当前是否正在运行。</summary>
  24. bool Running { get; }
  25. /// <summary>是否曾经有过未被取消且未失败的运行。</summary>
  26. bool HasSucceeded { get; }
  27. /// <summary>标识上次进入空闲时,并非因为取消或失败,而是正常运行到结束。</summary>
  28. bool LastSucceeded { get; }
  29. /// <summary>当前工作负载的执行进度。</summary>
  30. ProgressProvider Progress { get; }
  31. }
  32. /// <summary>
  33. /// 可合并和重启的工作器。
  34. /// <para/> 在工作负载运行期间多次调用 <see cref="Start(CancellationToken)"/> 会取消当前负载并使用最新令牌重新执行;多次调用也只重新执行一次。
  35. /// </summary>
  36. public abstract class RedoableWorkerBase<TOut>(Func<CancellationToken?, ProgressProvider?, TOut> workload,
  37. ProgressProvider? progress = null, [CallerMemberName] string creatorMemberName = "") : IWorker {
  38. // ============================================ 状态与事件 ============================================
  39. /// <inheritdoc/>
  40. public bool Running { get { lock (this) return running; } }
  41. private bool running;
  42. /// <inheritdoc/>
  43. public event Action? Started;
  44. /// <inheritdoc/>
  45. public event Action? Stopped;
  46. /// <inheritdoc/>
  47. public bool HasSucceeded { get { lock (this) return hasSucceeded; } }
  48. private bool hasSucceeded;
  49. /// <inheritdoc/>
  50. public event Action? Succeeded;
  51. /// <inheritdoc/>
  52. public event Action<Exception>? Failed;
  53. /// <inheritdoc/>
  54. public event Action? Canceled;
  55. /// <inheritdoc/>
  56. public bool LastSucceeded { get { lock (this) return lastSucceeded; } }
  57. private bool lastSucceeded;
  58. /// <summary>上次未被取消且未失败的运行中,工作负载的返回值。</summary>
  59. public TOut LastResult {
  60. get {
  61. lock (this) {
  62. if (typeof(TOut) == typeof(NoType)) throw new InvalidOperationException("该 Worker 没有返回值。");
  63. if (!hasSucceeded) throw new InvalidOperationException("从未成功完成过。");
  64. return lastResult == null ? default! : (TOut) lastResult;
  65. }
  66. }
  67. }
  68. private object? lastResult;
  69. /// <inheritdoc/>
  70. public ProgressProvider Progress { get; private set; } = progress ?? new ProgressProvider();
  71. private bool pendingRedo;
  72. // =========================================== 运行与取消 ===========================================
  73. private CancellationTokenSource? realCts;
  74. private CancellationToken lastToken;
  75. private readonly ManualResetEventSlim idleEvent = new(initialState: true);
  76. /// <summary>在工作线程运行工作负载。若当前已在运行,则取消当前负载并使用最新令牌重启。</summary>
  77. public void Start(CancellationToken cancellationToken = default, ProgressProvider? progressOverride = null) {
  78. // 接取运行状态
  79. lock (this) {
  80. lastToken = cancellationToken;
  81. if (progressOverride != null) Progress = progressOverride;
  82. if (running) {
  83. Logger.Info($"{creatorMemberName}:接到重启请求");
  84. pendingRedo = true;
  85. realCts?.Cancel();
  86. return;
  87. }
  88. running = true; idleEvent.Reset();
  89. realCts = CancellationTokenSource.CreateLinkedTokenSource(lastToken);
  90. }
  91. var th = new Thread(_Start) { IsBackground = true, Name = $"W/{creatorMemberName}" };
  92. th.Start();
  93. }
  94. private void _Start() {
  95. Logger.Info($"{creatorMemberName}:运行开始");
  96. Started?.Invoke();
  97. while (true) {
  98. try {
  99. realCts!.Token.ThrowIfCancellationRequested();
  100. Progress?.Reset();
  101. TOut result = workload(realCts.Token, Progress); // 实际的执行
  102. realCts.Token.ThrowIfCancellationRequested();
  103. lock (this) {
  104. realCts?.Dispose();
  105. if (pendingRedo) { // 接取重启请求
  106. pendingRedo = false;
  107. realCts = CancellationTokenSource.CreateLinkedTokenSource(lastToken);
  108. continue;
  109. }
  110. realCts = null;
  111. lastSucceeded = true;
  112. lastResult = result;
  113. hasSucceeded = true;
  114. running = false; idleEvent.Set();
  115. Progress?.Finish();
  116. }
  117. Logger.Info($"{creatorMemberName}:运行成功");
  118. Succeeded?.Invoke();
  119. } catch (Exception ex) {
  120. if (!ex.IsCanceled())
  121. Logger.Log(ex, $"{creatorMemberName}:运行失败{(pendingRedo ? ",但即将重启,或可忽略" : "")}",
  122. pendingRedo ? LogLevel.Warn : LogLevel.Error, LogBehavior.ToastIfDebug);
  123. lock (this) {
  124. realCts?.Dispose();
  125. if (pendingRedo) { // 接取重启请求
  126. Logger.Info($"{creatorMemberName}:重启开始");
  127. pendingRedo = false;
  128. realCts = CancellationTokenSource.CreateLinkedTokenSource(lastToken);
  129. continue;
  130. }
  131. realCts = null;
  132. lastSucceeded = false;
  133. running = false; idleEvent.Set();
  134. Progress?.Skip();
  135. }
  136. if (ex.IsCanceled()) {
  137. Logger.Info($"{creatorMemberName}:运行已取消");
  138. Canceled?.Invoke();
  139. } else {
  140. Failed?.Invoke(ex);
  141. }
  142. }
  143. break;
  144. }
  145. Stopped?.Invoke();
  146. }
  147. /// <inheritdoc/>
  148. public void Cancel() {
  149. lock (this) {
  150. pendingRedo = false;
  151. Logger.Info($"{creatorMemberName}:接到取消请求");
  152. realCts?.Cancel();
  153. }
  154. }
  155. /// <inheritdoc/>
  156. public bool WaitIfRunning(int millisecondsTimeout = -1, CancellationToken cancellationToken = default)
  157. => idleEvent.Wait(millisecondsTimeout, cancellationToken);
  158. /// <inheritdoc/>
  159. public async Task<bool> WaitIfRunningAsync(int millisecondsTimeout = -1, CancellationToken cancellationToken = default) {
  160. cancellationToken.ThrowIfCancellationRequested();
  161. var completionSource = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
  162. var waitHandle = ThreadPool.RegisterWaitForSingleObject(idleEvent.WaitHandle,
  163. (_, timedOut) => completionSource.TrySetResult(!timedOut), null, millisecondsTimeout, executeOnlyOnce: true);
  164. using var cancellationRegistration = cancellationToken.Register(() => completionSource.TrySetCanceled(cancellationToken));
  165. try {
  166. return await completionSource.Task.NoCapture();
  167. } finally {
  168. waitHandle.Unregister(null);
  169. }
  170. }
  171. }
  172. /// <inheritdoc />
  173. public class RedoableWorker<TOut> : RedoableWorkerBase<TOut> {
  174. public RedoableWorker(Func<CancellationToken?, ProgressProvider?, TOut> workload, [CallerMemberName] string creatorMemberName = "")
  175. : base(workload, creatorMemberName: creatorMemberName) { }
  176. public RedoableWorker(Func<CancellationToken?, TOut> workload, [CallerMemberName] string creatorMemberName = "")
  177. : base((c, _) => workload(c), creatorMemberName: creatorMemberName) { }
  178. public RedoableWorker(Func<TOut> workload, [CallerMemberName] string creatorMemberName = "")
  179. : base((_, _) => workload(), creatorMemberName: creatorMemberName) { }
  180. }
  181. /// <inheritdoc />
  182. public class RedoableWorker : RedoableWorkerBase<NoType?> {
  183. public RedoableWorker(Action<CancellationToken?, ProgressProvider?> workload, [CallerMemberName] string creatorMemberName = "")
  184. : base((c, p) => { workload(c, p); return null; }, creatorMemberName: creatorMemberName) { }
  185. public RedoableWorker(Action<CancellationToken?> workload, [CallerMemberName] string creatorMemberName = "")
  186. : base((c, _) => { workload(c); return null; }, creatorMemberName: creatorMemberName) { }
  187. public RedoableWorker(Action workload, [CallerMemberName] string creatorMemberName = "")
  188. : base((_, _) => { workload(); return null; }, creatorMemberName: creatorMemberName) { }
  189. }
  190. /// <summary>指示没有该类型,用于泛型参数。</summary>
  191. public class NoType { }