GroupHandlerIO.cs 4.3 KB

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