RedoableWorker.cs 8.0 KB

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