LoopWorker.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System;
  2. using System.Threading.Tasks;
  3. using Quadarax.Foundation.Core.Logging;
  4. namespace Quadarax.Foundation.Core.Thread
  5. {
  6. public class LoopWorker : AbstractWorker
  7. {
  8. #region *** Private fields ***
  9. private TimeSpan _defaultTimeout;
  10. private long _cntLimit;
  11. private Func<IWorkerContext, Task> _customIteration;
  12. #endregion
  13. #region *** Properties ***
  14. public long IterationsLimit { get; set; } = 0;
  15. public TimeSpan IterationsDelayBetween { get; set; } = TimeSpan.Zero;
  16. #endregion
  17. #region *** Constructors ***
  18. public LoopWorker(IWorkerContext context) : base(context)
  19. {
  20. }
  21. public LoopWorker(string workerName, IWorkerContext context) : base(workerName, context)
  22. {
  23. }
  24. public LoopWorker(string workerName) : base(workerName)
  25. {
  26. }
  27. public LoopWorker(string workerName, IWorkerContext context, ILogger logger = null) : base(workerName, context, logger)
  28. {
  29. }
  30. public LoopWorker(string workerName, IWorkerContext context,Func<IWorkerContext, Task> customIteration = null, ILogger logger = null) : base(workerName, context, logger)
  31. {
  32. _customIteration = customIteration;
  33. }
  34. #endregion
  35. #region *** Public Operations ***
  36. #endregion
  37. #region *** Virtuals and protected ***
  38. protected override async Task Do(IWorkerContext context)
  39. {
  40. var exit = false;
  41. var first = true;
  42. while (!exit)
  43. {
  44. if (first)
  45. first = false;
  46. else if (IterationsDelayBetween != TimeSpan.Zero)
  47. System.Threading.Thread.CurrentThread.Join(IterationsDelayBetween);
  48. if (IterationsLimit == 0)
  49. {
  50. if (_customIteration != null)
  51. await _customIteration(context);
  52. else
  53. await DoIteration(context);
  54. }
  55. else
  56. {
  57. if (_customIteration != null)
  58. await _customIteration(context);
  59. else
  60. await DoIteration(context);
  61. _cntLimit++;
  62. if (_cntLimit > IterationsLimit)
  63. exit = true;
  64. }
  65. }
  66. }
  67. #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
  68. protected virtual async Task DoIteration(IWorkerContext context)
  69. #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
  70. {
  71. }
  72. protected override void OnBeforeStart()
  73. {
  74. base.OnBeforeStart();
  75. _defaultTimeout = Timeout;
  76. Timeout = TimeSpan.Zero;
  77. }
  78. protected override void OnAfterStop()
  79. {
  80. base.OnAfterStop();
  81. Timeout = _defaultTimeout;
  82. _cntLimit = 0;
  83. }
  84. #endregion
  85. #region *** Private Operations ***
  86. #endregion
  87. }
  88. }