RedoableWorker.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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 (!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. Logger.Info($"{creatorMemberName}:接到重启请求");
  83. pendingRedo = true;
  84. realCts?.Cancel();
  85. return;
  86. }
  87. running = true; idleEvent.Reset();
  88. realCts = CancellationTokenSource.CreateLinkedTokenSource(lastToken);
  89. }
  90. var th = new Thread(_Start) { IsBackground = true, Name = $"W/{creatorMemberName}" };
  91. th.Start();
  92. }
  93. private void _Start() {
  94. Logger.Info($"{creatorMemberName}:运行开始");
  95. Started?.Invoke();
  96. while (true) {
  97. try {
  98. realCts!.Token.ThrowIfCancellationRequested();
  99. Progress?.Reset();
  100. TOut result = workload(realCts.Token, Progress); // 实际的执行
  101. realCts.Token.ThrowIfCancellationRequested();
  102. lock (this) {
  103. realCts?.Dispose();
  104. if (pendingRedo) { // 接取重启请求
  105. pendingRedo = false;
  106. realCts = CancellationTokenSource.CreateLinkedTokenSource(lastToken);
  107. continue;
  108. }
  109. realCts = null;
  110. lastSucceeded = true;
  111. lastResult = result;
  112. hasSucceeded = true;
  113. running = false; idleEvent.Set();
  114. Progress?.Finish();
  115. }
  116. Logger.Info($"{creatorMemberName}:运行成功");
  117. Succeeded?.Invoke();
  118. } catch (Exception ex) {
  119. if (!ex.IsCanceled())
  120. Logger.Log(ex, $"{creatorMemberName}:运行失败{(pendingRedo ? ",但即将重启,或可忽略" : "")}", pendingRedo ? LogLevel.Info : LogLevel.Warn);
  121. lock (this) {
  122. realCts?.Dispose();
  123. if (pendingRedo) { // 接取重启请求
  124. Logger.Info($"{creatorMemberName}:重启开始");
  125. pendingRedo = false;
  126. realCts = CancellationTokenSource.CreateLinkedTokenSource(lastToken);
  127. continue;
  128. }
  129. realCts = null;
  130. lastSucceeded = false;
  131. running = false; idleEvent.Set();
  132. Progress?.Skip();
  133. }
  134. if (ex.IsCanceled()) {
  135. Logger.Info($"{creatorMemberName}:运行已取消");
  136. Canceled?.Invoke();
  137. } else {
  138. Failed?.Invoke(ex);
  139. }
  140. }
  141. break;
  142. }
  143. Stopped?.Invoke();
  144. }
  145. /// <inheritdoc/>
  146. public void Cancel() {
  147. lock (this) {
  148. pendingRedo = false;
  149. Logger.Info($"{creatorMemberName}:接到取消请求");
  150. realCts?.Cancel();
  151. }
  152. }
  153. /// <inheritdoc/>
  154. public bool WaitIfRunning(int millisecondsTimeout = -1, CancellationToken cancellationToken = default)
  155. => idleEvent.Wait(millisecondsTimeout, cancellationToken);
  156. /// <inheritdoc/>
  157. public async Task<bool> WaitIfRunningAsync(int millisecondsTimeout = -1, CancellationToken cancellationToken = default) {
  158. cancellationToken.ThrowIfCancellationRequested();
  159. var completionSource = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
  160. var waitHandle = ThreadPool.RegisterWaitForSingleObject(idleEvent.WaitHandle,
  161. (_, timedOut) => completionSource.TrySetResult(!timedOut), null, millisecondsTimeout, executeOnlyOnce: true);
  162. using var cancellationRegistration = cancellationToken.Register(() => completionSource.TrySetCanceled(cancellationToken));
  163. try {
  164. return await completionSource.Task;
  165. } finally {
  166. waitHandle.Unregister(null);
  167. }
  168. }
  169. }
  170. /// <inheritdoc />
  171. public class RedoableWorker<TOut> : RedoableWorkerBase<TOut> {
  172. public RedoableWorker(Func<CancellationToken?, ProgressProvider?, TOut> workload, [CallerMemberName] string creatorMemberName = "")
  173. : base(workload, creatorMemberName: creatorMemberName) { }
  174. public RedoableWorker(Func<CancellationToken?, TOut> workload, [CallerMemberName] string creatorMemberName = "")
  175. : base((c, _) => workload(c), creatorMemberName: creatorMemberName) { }
  176. public RedoableWorker(Func<TOut> workload, [CallerMemberName] string creatorMemberName = "")
  177. : base((_, _) => workload(), creatorMemberName: creatorMemberName) { }
  178. }
  179. /// <inheritdoc />
  180. public class RedoableWorker : RedoableWorkerBase<object?> {
  181. public RedoableWorker(Action<CancellationToken?, ProgressProvider?> workload, [CallerMemberName] string creatorMemberName = "")
  182. : base((c, p) => { workload(c, p); return null; }, creatorMemberName: creatorMemberName) { }
  183. public RedoableWorker(Action<CancellationToken?> workload, [CallerMemberName] string creatorMemberName = "")
  184. : base((c, _) => { workload(c); return null; }, creatorMemberName: creatorMemberName) { }
  185. public RedoableWorker(Action workload, [CallerMemberName] string creatorMemberName = "")
  186. : base((_, _) => { workload(); return null; }, creatorMemberName: creatorMemberName) { }
  187. }