RedoableWorker.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. namespace MeloongCore;
  2. /// <summary>
  3. /// 可合并和重启的工作器。
  4. /// <para/> 在工作负载运行期间多次调用 <see cref="Invoke(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 Invoke(CancellationToken cancellationToken = default);
  15. /// <summary>取消当前运行。</summary>
  16. void Cancel();
  17. /// <summary>仅在当前处于运行状态时,等待其完成。</summary>
  18. /// <returns>若未超时则返回 true。</returns>
  19. bool WaitIfRunning(int millisecondsTimeout = -1);
  20. }
  21. /// <inheritdoc cref="IRedoableWorker"/>
  22. public abstract class RedoableWorkerBase<TOut>(Func<CancellationToken?, ProgressProvider?, TOut> workload, ProgressProvider? p = null) : IRedoableWorker {
  23. // ============================================ 状态与事件 ============================================
  24. /// <inheritdoc/>
  25. public bool Running { get { lock (this) return running; } }
  26. private bool running;
  27. /// <summary>从空闲状态进入运行状态时触发。</summary>
  28. public event Action? Started;
  29. /// <summary>运行结束并进入空闲状态时触发。</summary>
  30. public event Action? Stopped;
  31. /// <inheritdoc/>
  32. public bool HasSucceeded { get { lock (this) return hasSucceeded; } }
  33. private bool hasSucceeded;
  34. /// <summary>工作负载成功完成时触发,参数为返回值。这可能会在重启前触发。</summary>
  35. public event Action<TOut>? Succeeded;
  36. /// <summary>工作负载执行失败时触发,参数为发生的异常。这可能会在重启前触发。</summary>
  37. public event Action<Exception>? Failed;
  38. /// <summary>运行被取消时触发。这可能会在重启前触发。</summary>
  39. public event Action? Canceled;
  40. /// <inheritdoc/>
  41. public bool LastSucceeded { get { lock (this) return lastSucceeded; } }
  42. private bool lastSucceeded;
  43. /// <summary>上次未被取消且未失败的运行中,工作负载的返回值。</summary>
  44. public TOut LastResult {
  45. get {
  46. lock (this) {
  47. if (!hasSucceeded) throw new InvalidOperationException("从未成功完成过。");
  48. return lastResult == null ? default! : (TOut) lastResult;
  49. }
  50. }
  51. }
  52. private object? lastResult;
  53. private bool pendingRedo;
  54. // =========================================== 运行与取消 ===========================================
  55. private CancellationTokenSource? realCts;
  56. private CancellationToken lastToken;
  57. private readonly ManualResetEventSlim idleEvent = new(initialState: true);
  58. /// <inheritdoc/>
  59. public void Invoke(CancellationToken cancellationToken = default) {
  60. // 接取运行状态
  61. lock (this) {
  62. lastToken = cancellationToken;
  63. if (running) {
  64. pendingRedo = true;
  65. realCts?.Cancel();
  66. return;
  67. }
  68. running = true; idleEvent.Reset();
  69. realCts = CancellationTokenSource.CreateLinkedTokenSource(lastToken);
  70. }
  71. var th = new Thread(_Invoke) { IsBackground = true };
  72. th.Start();
  73. }
  74. private void _Invoke() {
  75. Started?.Invoke();
  76. while (true) {
  77. try {
  78. realCts!.Token.ThrowIfCancellationRequested();
  79. p?.Reset();
  80. TOut result = workload(realCts.Token, p); // 实际的执行
  81. realCts.Token.ThrowIfCancellationRequested();
  82. lock (this) {
  83. realCts?.Dispose();
  84. if (pendingRedo) { // 接取重启请求
  85. pendingRedo = false;
  86. realCts = CancellationTokenSource.CreateLinkedTokenSource(lastToken);
  87. continue;
  88. }
  89. realCts = null;
  90. lastSucceeded = true;
  91. lastResult = result;
  92. hasSucceeded = true;
  93. running = false; idleEvent.Set();
  94. }
  95. Succeeded?.Invoke(result);
  96. } catch (Exception ex) {
  97. if (ex.IsCanceled()) {
  98. Canceled?.Invoke();
  99. } else {
  100. Failed?.Invoke(ex);
  101. Logger.Log(ex, $"工作线程执行失败{(pendingRedo ? ",但即将重启,或可忽略" : "")}", pendingRedo ? LogLevel.Info : LogLevel.Warn);
  102. }
  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 = false;
  112. running = false; idleEvent.Set();
  113. }
  114. }
  115. break;
  116. }
  117. Stopped?.Invoke();
  118. }
  119. /// <inheritdoc/>
  120. public void Cancel() {
  121. lock (this) {
  122. pendingRedo = false;
  123. realCts?.Cancel();
  124. }
  125. }
  126. /// <inheritdoc/>
  127. public bool WaitIfRunning(int millisecondsTimeout = -1)
  128. => idleEvent.Wait(millisecondsTimeout);
  129. }
  130. /// <inheritdoc />
  131. public class RedoableWorker<TOut> : RedoableWorkerBase<TOut> {
  132. public RedoableWorker(Func<CancellationToken?, ProgressProvider?, TOut> workload) : base(workload) { }
  133. public RedoableWorker(Func<CancellationToken?, TOut> workload) : base((c, _) => workload(c)) { }
  134. public RedoableWorker(Func<TOut> workload) : base((_, _) => workload()) { }
  135. }
  136. /// <inheritdoc />
  137. public class RedoableWorker : RedoableWorkerBase<object?> {
  138. public RedoableWorker(Func<CancellationToken?, ProgressProvider?, object?> workload) : base(workload) { }
  139. public RedoableWorker(Action<CancellationToken?> workload) : base((c, _) => { workload(c); return null; }) { }
  140. public RedoableWorker(Action workload) : base((_, _) => { workload(); return null; }) { }
  141. }