LoopWorker.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. #endregion
  12. #region *** Properties ***
  13. public long IterationsLimit { get; set; } = 0;
  14. public TimeSpan IterationsDelayBetween { get; set; } = TimeSpan.Zero;
  15. #endregion
  16. #region *** Constructors ***
  17. public LoopWorker(IWorkerContext context) : base(context)
  18. {
  19. }
  20. public LoopWorker(string workerName, IWorkerContext context) : base(workerName, context)
  21. {
  22. }
  23. public LoopWorker(string workerName) : base(workerName)
  24. {
  25. }
  26. public LoopWorker(string workerName, IWorkerContext context, ILogger logger = null) : base(workerName, context, logger)
  27. {
  28. }
  29. #endregion
  30. #region *** Public Operations ***
  31. #endregion
  32. #region *** Virtuals and protected ***
  33. protected override async Task Do(IWorkerContext context)
  34. {
  35. var exit = false;
  36. var first = true;
  37. while (!exit)
  38. {
  39. if (first)
  40. first = false;
  41. else if (IterationsDelayBetween != TimeSpan.Zero)
  42. System.Threading.Thread.CurrentThread.Join(IterationsDelayBetween);
  43. if (IterationsLimit == 0)
  44. {
  45. await DoIteration(context);
  46. }
  47. else
  48. {
  49. await DoIteration(context);
  50. _cntLimit++;
  51. if (_cntLimit > IterationsLimit)
  52. exit = true;
  53. }
  54. }
  55. }
  56. protected virtual async Task DoIteration(IWorkerContext context)
  57. {
  58. }
  59. protected override void OnBeforeStart()
  60. {
  61. base.OnBeforeStart();
  62. _defaultTimeout = Timeout;
  63. Timeout = TimeSpan.Zero;
  64. }
  65. protected override void OnAfterStop()
  66. {
  67. base.OnAfterStop();
  68. Timeout = _defaultTimeout;
  69. _cntLimit = 0;
  70. }
  71. #endregion
  72. #region *** Private Operations ***
  73. #endregion
  74. }
  75. }