CTaskAwaitBufferT.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace Fort23.Core
  5. {
  6. public class CTaskAwaitBuffer<T> : IDisposable where T : new()
  7. {
  8. private List<CTask<T>> _cTasks = new List<CTask<T>>();
  9. private List<T> _results = new List<T>();
  10. public CTask<T>[] GetTask
  11. {
  12. get { return _cTasks.ToArray(); }
  13. }
  14. private int count;
  15. private CTask CTask;
  16. private bool _isWait;
  17. public T[] GetResults()
  18. {
  19. return _results.ToArray();
  20. }
  21. public List<T> GetResultsLists()
  22. {
  23. return _results.ToList();
  24. }
  25. public void Clear()
  26. {
  27. _cTasks.Clear();
  28. _isWait = false;
  29. CTask = null;
  30. count = 0;
  31. }
  32. public void AddTask(CTask<T> icTaskResult)
  33. {
  34. _cTasks.Add(icTaskResult);
  35. if (_isWait)
  36. {
  37. count++;
  38. AwaitTask(icTaskResult);
  39. }
  40. }
  41. public async CTask<List<T>> WaitAll()
  42. {
  43. _isWait = true;
  44. count += _cTasks.Count;
  45. if (count == 0)
  46. {
  47. return new List<T>();
  48. }
  49. CTask = CTask.Create(false);
  50. CTask<T>[] icTaskResults = _cTasks.ToArray();
  51. for (int i = 0; i < icTaskResults.Length; i++)
  52. {
  53. AwaitTask(icTaskResults[i]);
  54. }
  55. await CTask;
  56. return new List<T>(_results);
  57. }
  58. public async CTask AwaitTask(CTask<T> icTaskResult)
  59. {
  60. T result = await icTaskResult;
  61. _results.Add(result);
  62. count--;
  63. // _cTasks.Remove(icTaskResult);
  64. if (count <= 0 && _isWait)
  65. {
  66. _isWait = false;
  67. CTask cta = CTask;
  68. // if (_cTasks != null)
  69. // {
  70. // _cTasks.Clear();
  71. // }
  72. count = 0;
  73. cta.SetResult();
  74. }
  75. }
  76. public void Dispose()
  77. {
  78. _cTasks.Clear();
  79. _results.Clear();
  80. CTask = null;
  81. _isWait = false;
  82. }
  83. }
  84. }