GroupHandlerIO.cs 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. using Microsoft.Extensions.Logging;
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace EVCB_OCPP.WSServer.Helper;
  10. public class GroupHandler<TI,TO> where TI : class
  11. {
  12. public GroupHandler(
  13. Func<BundleHandlerData<TI,TO>, Task> handleFunc,
  14. ILogger logger, int workerCnt = 1, int maxRetry = 10)
  15. {
  16. this.handleFunc = handleFunc;
  17. this.logger = logger;
  18. this.maxRetry = maxRetry;
  19. workersLock = new SemaphoreSlim(workerCnt);
  20. //singleWorkLock = new(_WorkerCnt);
  21. }
  22. private readonly Func<BundleHandlerData<TI, TO>, Task> handleFunc;
  23. private readonly ILogger logger;
  24. private readonly int maxRetry;
  25. private readonly ConcurrentQueue<WaitParam<TI, TO>> waitList = new();
  26. private SemaphoreSlim workersLock;// = new SemaphoreSlim(1);
  27. public async Task<TO> HandleAsync(TI param)
  28. {
  29. var waitData = new WaitParam<TI,TO>() { Data = param, Waiter = new SemaphoreSlim(0), Exception = null };
  30. waitList.Enqueue(waitData);
  31. TryStartHandler();
  32. await waitData.Waiter.WaitAsync();
  33. if (waitData.Exception is not null)
  34. {
  35. throw waitData.Exception;
  36. }
  37. return waitData.Result;
  38. }
  39. private void TryStartHandler()
  40. {
  41. if (!workersLock.Wait(0))
  42. {
  43. return;
  44. }
  45. if (waitList.Count == 0)
  46. {
  47. workersLock.Release();
  48. return;
  49. }
  50. _ = StartHandleTask();
  51. }
  52. private async Task StartHandleTask()
  53. {
  54. var timer = Stopwatch.StartNew();
  55. List<long> times = new();
  56. var requests = new List<WaitParam<TI,TO>>();
  57. while (waitList.TryDequeue(out var handle))
  58. {
  59. requests.Add(handle);
  60. }
  61. times.Add(timer.ElapsedMilliseconds);
  62. int cnt = 0;
  63. Exception lastException = null;
  64. var datas = requests.Select(x => x.Data).ToList();
  65. for (; cnt < maxRetry; cnt++)
  66. {
  67. var bundleHandledata = new BundleHandlerData<TI, TO>(datas);
  68. try
  69. {
  70. await handleFunc(bundleHandledata);
  71. }
  72. catch (Exception e)
  73. {
  74. lastException = e;
  75. }
  76. var completedKeys = bundleHandledata.CompletedDatas.Select(x => x.Key).ToList();
  77. var completedRequests = requests.Where(x => completedKeys.Any(y=> y == x.Data)).ToList();
  78. foreach (var request in completedRequests)
  79. {
  80. var result = bundleHandledata.CompletedDatas.FirstOrDefault(x => x.Key == request.Data);
  81. request.Result = result.Value;
  82. request.Waiter.Release();
  83. }
  84. //datas = datas.Except(bundleHandledata.CompletedDatas).ToList();
  85. datas = datas.Where(x => !completedKeys.Contains(x)).ToList();
  86. if (datas == null || datas.Count == 0)
  87. {
  88. break;
  89. }
  90. logger.LogError(lastException?.Message);
  91. times.Add(timer.ElapsedMilliseconds);
  92. }
  93. var uncompletedRequests = requests.Where(x => datas.Contains(x.Data)).ToList();
  94. foreach (var request in uncompletedRequests)
  95. {
  96. request.Exception = lastException;
  97. request.Waiter.Release();
  98. }
  99. workersLock.Release();
  100. timer.Stop();
  101. if (timer.ElapsedMilliseconds > 1000)
  102. {
  103. logger.LogWarning($"StartHandleTask {string.Join("/", times)}");
  104. }
  105. TryStartHandler();
  106. }
  107. }
  108. public class BundleHandlerData<TI,TO>
  109. {
  110. public List<TI> Datas { get; set; }
  111. public List<KeyValuePair<TI,TO>> CompletedDatas { get; set; }
  112. public BundleHandlerData(List<TI> datas)
  113. {
  114. Datas = datas;
  115. CompletedDatas = new();
  116. }
  117. public void AddCompletedData(TI competedData, TO result)
  118. {
  119. CompletedDatas.Add(new KeyValuePair<TI, TO>(competedData, result)); ;
  120. }
  121. }
  122. internal class WaitParam<TI,TO>
  123. {
  124. public TI Data { get; init; }
  125. public TO Result { get; set; }
  126. public SemaphoreSlim Waiter { get; init; }
  127. public Exception Exception { get; set; }
  128. }