Worker.cs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. namespace MeloongCore;
  2. /// <summary>
  3. /// 可合并和重启的工作器。
  4. /// <para/> 在工作负载运行期间多次调用 <see cref="Run()"/> 会取消当前负载并使用最新令牌重新执行;多次调用也只重新执行一次。
  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 Run(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, TOut> workload) : IRedoableWorker {
  23. // ============================================ 状态 ============================================
  24. /// <inheritdoc/>
  25. public bool Running { get { lock (this) return running; } }
  26. private bool running;
  27. /// <inheritdoc/>
  28. public bool HasSucceeded { get { lock (this) return hasSucceeded; } }
  29. private bool hasSucceeded;
  30. /// <inheritdoc/>
  31. public bool LastSucceeded { get { lock (this) return lastSucceeded; } }
  32. private bool lastSucceeded;
  33. /// <summary>上次未被取消且未失败的运行中,工作负载的返回值。</summary>
  34. public TOut LastResult {
  35. get {
  36. lock (this) {
  37. if (!hasSucceeded) throw new InvalidOperationException("从未成功完成过。");
  38. return lastResult == null ? default! : (TOut) lastResult;
  39. }
  40. }
  41. }
  42. private object? lastResult;
  43. private bool pendingRedo;
  44. // =========================================== 运行与取消 ===========================================
  45. private CancellationTokenSource? realCts;
  46. private CancellationToken lastToken;
  47. private readonly ManualResetEventSlim idleEvent = new(initialState: true);
  48. /// <inheritdoc/>
  49. public void Run(CancellationToken cancellationToken = default) {
  50. // 接取运行状态
  51. lock (this) {
  52. lastToken = cancellationToken;
  53. if (running) {
  54. pendingRedo = true;
  55. realCts?.Cancel();
  56. return;
  57. }
  58. running = true; idleEvent.Reset();
  59. realCts = CancellationTokenSource.CreateLinkedTokenSource(lastToken);
  60. }
  61. var th = new Thread(_Run) { IsBackground = true };
  62. th.Start();
  63. }
  64. private void _Run() {
  65. while (true) {
  66. try {
  67. realCts!.Token.ThrowIfCancellationRequested();
  68. TOut result = workload(realCts.Token); // 实际的执行
  69. realCts.Token.ThrowIfCancellationRequested();
  70. lock (this) {
  71. realCts?.Dispose();
  72. if (pendingRedo) { // 接取重启请求
  73. pendingRedo = false;
  74. realCts = CancellationTokenSource.CreateLinkedTokenSource(lastToken);
  75. continue;
  76. }
  77. realCts = null;
  78. lastSucceeded = true;
  79. lastResult = result;
  80. hasSucceeded = true;
  81. running = false; idleEvent.Set();
  82. }
  83. } catch (Exception ex) {
  84. if (!ex.IsCanceled())
  85. Logger.Log(ex, $"工作线程执行失败{(pendingRedo ? ",但即将重启,或可忽略" : "")}", pendingRedo ? LogLevel.Info : LogLevel.Warn);
  86. lock (this) {
  87. realCts?.Dispose();
  88. if (pendingRedo) { // 接取重启请求
  89. pendingRedo = false;
  90. realCts = CancellationTokenSource.CreateLinkedTokenSource(lastToken);
  91. continue;
  92. }
  93. realCts = null;
  94. lastSucceeded = false;
  95. running = false; idleEvent.Set();
  96. }
  97. }
  98. return;
  99. }
  100. }
  101. /// <inheritdoc/>
  102. public void Cancel() {
  103. lock (this) {
  104. pendingRedo = false;
  105. realCts?.Cancel();
  106. }
  107. }
  108. /// <inheritdoc/>
  109. public bool WaitIfRunning(int millisecondsTimeout = -1)
  110. => idleEvent.Wait(millisecondsTimeout);
  111. }
  112. /// <inheritdoc />
  113. public sealed class RedoableWorker<TOut> : RedoableWorkerBase<TOut> {
  114. public RedoableWorker(Func<CancellationToken, TOut> workload) : base(workload) { }
  115. public RedoableWorker(Func<TOut> workload) : base(_ => workload()) { }
  116. }
  117. /// <inheritdoc />
  118. public sealed class RedoableWorker : RedoableWorkerBase<object?> {
  119. public RedoableWorker(Action<CancellationToken> workload) : base(ct => { workload(ct); return null; }) { }
  120. public RedoableWorker(Action workload) : base(_ => { workload(); return null; }) { }
  121. }