DynamicExecutor.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace WingServerCommon.Utilities.Executors
  5. {
  6. /// <summary>
  7. /// The DynamicExecutor provide the ability that can active one worker and let it run first.
  8. /// </summary>
  9. /// <typeparam name="T"></typeparam>
  10. public class DynamicExecutor<T> : ExecutorBase<T> where T : class, IIdContext
  11. {
  12. private readonly List<ExecuteWorker<T>> _workers = new List<ExecuteWorker<T>>();
  13. public DynamicExecutor(string name) : base(name)
  14. {
  15. }
  16. protected DynamicExecutor(string name, TimeSpan executeDelayTime) : base(name, executeDelayTime)
  17. {
  18. }
  19. /// <summary>
  20. /// Activate one worker so that it can run first.
  21. /// </summary>
  22. /// <param name="contextId"></param>
  23. public void ActivateWorker(string contextId)
  24. {
  25. lock (WorkersLocker)
  26. {
  27. var worker = _workers.FirstOrDefault(x => x.Parameter.Id == contextId);
  28. if (worker != null && _workers.IndexOf(worker) != 0)
  29. {
  30. _workers.Remove(worker);
  31. _workers.Insert(0, worker);
  32. }
  33. }
  34. }
  35. /// <summary>
  36. /// Indicate whether all works already contain the item.
  37. /// </summary>
  38. /// <param name="contextId">context id.</param>
  39. /// <returns>True if contains.</returns>
  40. public bool ContainsWorker(string contextId)
  41. {
  42. lock (WorkersLocker)
  43. {
  44. return _workers.Any(m => m.Parameter.Id == contextId);
  45. }
  46. }
  47. /// <summary>
  48. /// Gets current worker count in queue.
  49. /// </summary>
  50. /// <returns></returns>
  51. protected override int GetWorkerCount()
  52. {
  53. return _workers.Count;
  54. }
  55. /// <summary>
  56. /// Add one worker into the queue.
  57. /// </summary>
  58. /// <param name="worker"></param>
  59. protected override void AddWorker(ExecuteWorker<T> worker)
  60. {
  61. _workers.Add(worker);
  62. }
  63. /// <summary>
  64. /// Take one worker from the queue.
  65. /// </summary>
  66. /// <returns></returns>
  67. protected override ExecuteWorker<T> TakeWorker()
  68. {
  69. var worker = _workers.FirstOrDefault();
  70. if (worker != null)
  71. {
  72. _workers.Remove(worker);
  73. }
  74. return worker;
  75. }
  76. /// <summary>
  77. /// Gets all workers.
  78. /// </summary>
  79. /// <returns></returns>
  80. protected override IEnumerable<ExecuteWorker<T>> GetWorkers()
  81. {
  82. return _workers.ToArray();
  83. }
  84. /// <summary>
  85. /// Clear all workers which not stated.
  86. /// </summary>
  87. protected override void CancelWorkers()
  88. {
  89. _workers.Clear();
  90. }
  91. }
  92. }