TaskSlots.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using Quadarax.Foundation.Core.Business.Processor.Enums;
  2. using Quadarax.Foundation.Core.Business.Processor.Task;
  3. using Quadarax.Foundation.Core.Logging;
  4. namespace Quadarax.Foundation.Core.Business.Processor.Queue
  5. {
  6. internal class TaskSlots
  7. {
  8. #region *** Properties ***
  9. public int FreeSlotsCount => _taskSlots.Count(x => x == null);
  10. #endregion
  11. #region *** Fields ***
  12. private ITaskItem?[] _taskSlots;
  13. private readonly ILog _log;
  14. #endregion
  15. #region *** Indexer ***
  16. public ITaskItem? this[int ordinal] => GetSlot(ordinal);
  17. #endregion
  18. #region *** Constructor ***
  19. public TaskSlots(int initialMaxSlots)
  20. {
  21. _taskSlots = new ITaskItem?[initialMaxSlots];
  22. _log = new ConsoleLogger().GetLogger(nameof(TaskSlots));
  23. }
  24. #endregion
  25. #region *** Public Operations ***
  26. public int AssignSlot(ITaskItem task)
  27. {
  28. if(task == null) throw new ArgumentNullException(nameof(task));
  29. var ordinal = GetNextFreeSlotOrdinal();
  30. if (ordinal == -1) return -1;
  31. _taskSlots[ordinal] = task;
  32. _log.Log(LogSeverityEnum.Debug, $"Task ({task}) assigned to slot # {ordinal}");
  33. return ordinal;
  34. }
  35. public ITaskItem? GetSlot(int ordinal)
  36. {
  37. if (ordinal < 0 || ordinal >= _taskSlots.Length) throw new ArgumentOutOfRangeException(nameof(ordinal));
  38. return _taskSlots[ordinal];
  39. }
  40. public void ReleaseSlot(int ordinal)
  41. {
  42. var task = GetSlot(ordinal);
  43. if (task == null) return;
  44. if (task.Status == ProcessStatusEnum.Started)
  45. task.Stop("(System) Paused due change configuration.", true, false);
  46. _taskSlots[ordinal] = null;
  47. _log.Log(LogSeverityEnum.Debug, $"Task ({task}) was released from slot # {ordinal}");
  48. }
  49. public void ReleaseAll()
  50. {
  51. _log.Log(LogSeverityEnum.Debug, "Releasing all slots ...");
  52. for (var a = 0; a < _taskSlots.Length; a++)
  53. ReleaseSlot(a);
  54. }
  55. public void SetMaxSlots(int maxSlots)
  56. {
  57. _log.Log(LogSeverityEnum.Debug, $"Set max slots from {_taskSlots.Length} to {maxSlots}");
  58. if (maxSlots < 1) throw new ArgumentOutOfRangeException(nameof(maxSlots));
  59. ReleaseAll();
  60. _taskSlots = new ITaskItem[maxSlots];
  61. }
  62. #endregion
  63. #region *** Private Operations ***
  64. private int GetNextFreeSlotOrdinal()
  65. {
  66. for (var i = 0; i < _taskSlots.Length; i++)
  67. {
  68. if (_taskSlots[i] == null) return i;
  69. }
  70. return -1;
  71. }
  72. #endregion
  73. }
  74. }