LoopWorker.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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, IQLogger 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. IterationCount++;
  55. }
  56. }
  57. protected virtual async Task DoIteration(IWorkerContext context)
  58. {
  59. }
  60. protected override void OnBeforeStart()
  61. {
  62. base.OnBeforeStart();
  63. _defaultTimeout = Timeout;
  64. Timeout = TimeSpan.Zero;
  65. }
  66. protected override void OnAfterStop()
  67. {
  68. base.OnAfterStop();
  69. Timeout = _defaultTimeout;
  70. _cntLimit = 0;
  71. }
  72. #endregion
  73. #region *** Private Operations ***
  74. #endregion
  75. }
  76. }