RedoableWorker.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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. // TODO: 现在的可观测性不佳,考虑增加调用方信息以及自身名称等,输出到日志,例如 CallerArgumentExpression
  33. /// <summary>
  34. /// 可合并和重启的工作器。
  35. /// <para/> 在工作负载运行期间多次调用 <see cref="Start(CancellationToken)"/> 会取消当前负载并使用最新令牌重新执行;多次调用也只重新执行一次。
  36. /// </summary>
  37. public abstract class RedoableWorkerBase<TOut>(Func<CancellationToken?, ProgressProvider?, TOut> workload, ProgressProvider? progress = null) : 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 (!hasSucceeded) throw new InvalidOperationException("从未成功完成过。");
  63. return lastResult == null ? default! : (TOut) lastResult;
  64. }
  65. }
  66. }
  67. private object? lastResult;
  68. /// <inheritdoc/>
  69. public ProgressProvider Progress { get; private set; } = progress ?? new ProgressProvider();
  70. private bool pendingRedo;
  71. // =========================================== 运行与取消 ===========================================
  72. private CancellationTokenSource? realCts;
  73. private CancellationToken lastToken;
  74. private readonly ManualResetEventSlim idleEvent = new(initialState: true);
  75. /// <summary>在工作线程运行工作负载。若当前已在运行,则取消当前负载并使用最新令牌重启。</summary>
  76. public void Start(CancellationToken cancellationToken = default, ProgressProvider? progressOverride = null) {
  77. // 接取运行状态
  78. lock (this) {
  79. lastToken = cancellationToken;
  80. if (progressOverride != null) Progress = progressOverride;
  81. if (running) {
  82. pendingRedo = true;
  83. realCts?.Cancel();
  84. return;
  85. }
  86. running = true; idleEvent.Reset();
  87. realCts = CancellationTokenSource.CreateLinkedTokenSource(lastToken);
  88. }
  89. var th = new Thread(_Start) { IsBackground = true, Name = nameof(RedoableWorker) };
  90. th.Start();
  91. }
  92. private void _Start() {
  93. Started?.Invoke();
  94. while (true) {
  95. try {
  96. realCts!.Token.ThrowIfCancellationRequested();
  97. Progress?.Reset();
  98. TOut result = workload(realCts.Token, Progress); // 实际的执行
  99. realCts.Token.ThrowIfCancellationRequested();
  100. lock (this) {
  101. realCts?.Dispose();
  102. if (pendingRedo) { // 接取重启请求
  103. pendingRedo = false;
  104. realCts = CancellationTokenSource.CreateLinkedTokenSource(lastToken);
  105. continue;
  106. }
  107. realCts = null;
  108. lastSucceeded = true;
  109. lastResult = result;
  110. hasSucceeded = true;
  111. running = false; idleEvent.Set();
  112. Progress?.Finish();
  113. }
  114. Succeeded?.Invoke();
  115. } catch (Exception ex) {
  116. if (!ex.IsCanceled())
  117. Logger.Log(ex, $"工作线程执行失败{(pendingRedo ? ",但即将重启,或可忽略" : "")}", pendingRedo ? LogLevel.Info : LogLevel.Warn);
  118. lock (this) {
  119. realCts?.Dispose();
  120. if (pendingRedo) { // 接取重启请求
  121. pendingRedo = false;
  122. realCts = CancellationTokenSource.CreateLinkedTokenSource(lastToken);
  123. continue;
  124. }
  125. realCts = null;
  126. lastSucceeded = false;
  127. running = false; idleEvent.Set();
  128. Progress?.Skip();
  129. }
  130. if (ex.IsCanceled()) {
  131. Canceled?.Invoke();
  132. } else {
  133. Failed?.Invoke(ex);
  134. }
  135. }
  136. break;
  137. }
  138. Stopped?.Invoke();
  139. }
  140. /// <inheritdoc/>
  141. public void Cancel() {
  142. lock (this) {
  143. pendingRedo = false;
  144. realCts?.Cancel();
  145. }
  146. }
  147. /// <inheritdoc/>
  148. public bool WaitIfRunning(int millisecondsTimeout = -1, CancellationToken cancellationToken = default)
  149. => idleEvent.Wait(millisecondsTimeout, cancellationToken);
  150. /// <inheritdoc/>
  151. public async Task<bool> WaitIfRunningAsync(int millisecondsTimeout = -1, CancellationToken cancellationToken = default) {
  152. cancellationToken.ThrowIfCancellationRequested();
  153. var completionSource = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
  154. var waitHandle = ThreadPool.RegisterWaitForSingleObject(idleEvent.WaitHandle,
  155. (_, timedOut) => completionSource.TrySetResult(!timedOut), null, millisecondsTimeout, executeOnlyOnce: true);
  156. using var cancellationRegistration = cancellationToken.Register(() => completionSource.TrySetCanceled(cancellationToken));
  157. try {
  158. return await completionSource.Task;
  159. } finally {
  160. waitHandle.Unregister(null);
  161. }
  162. }
  163. }
  164. /// <inheritdoc />
  165. public class RedoableWorker<TOut> : RedoableWorkerBase<TOut> {
  166. public RedoableWorker(Func<CancellationToken?, ProgressProvider?, TOut> workload) : base(workload) { }
  167. public RedoableWorker(Func<CancellationToken?, TOut> workload) : base((c, _) => workload(c)) { }
  168. public RedoableWorker(Func<TOut> workload) : base((_, _) => workload()) { }
  169. }
  170. /// <inheritdoc />
  171. public class RedoableWorker : RedoableWorkerBase<object?> {
  172. public RedoableWorker(Action<CancellationToken?, ProgressProvider?> workload) : base((c, p) => { workload(c, p); return null; }) { }
  173. public RedoableWorker(Action<CancellationToken?> workload) : base((c, _) => { workload(c); return null; }) { }
  174. public RedoableWorker(Action workload) : base((_, _) => { workload(); return null; }) { }
  175. }