CTaskAwaitBufferT.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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 void Clear()
  22. {
  23. _cTasks.Clear();
  24. _isWait = false;
  25. CTask = null;
  26. count = 0;
  27. }
  28. public void AddTask(CTask<T> icTaskResult)
  29. {
  30. _cTasks.Add(icTaskResult);
  31. if (_isWait)
  32. {
  33. count++;
  34. AwaitTask(icTaskResult);
  35. }
  36. }
  37. public async CTask<List<T>> WaitAll()
  38. {
  39. _isWait = true;
  40. count += _cTasks.Count;
  41. if (count == 0)
  42. {
  43. return new List<T>();
  44. }
  45. CTask = CTask.Create(false);
  46. CTask<T>[] icTaskResults = _cTasks.ToArray();
  47. for (int i = 0; i < icTaskResults.Length; i++)
  48. {
  49. AwaitTask(icTaskResults[i]);
  50. }
  51. await CTask;
  52. return new List<T>(_results);
  53. }
  54. public async CTask AwaitTask(CTask<T> icTaskResult)
  55. {
  56. T result = await icTaskResult;
  57. _results.Add(result);
  58. count--;
  59. // _cTasks.Remove(icTaskResult);
  60. if (count <= 0 && _isWait)
  61. {
  62. _isWait = false;
  63. CTask cta = CTask;
  64. // if (_cTasks != null)
  65. // {
  66. // _cTasks.Clear();
  67. // }
  68. count = 0;
  69. cta.SetResult();
  70. }
  71. }
  72. public void Dispose()
  73. {
  74. _cTasks.Clear();
  75. _results.Clear();
  76. CTask = null;
  77. _isWait = false;
  78. }
  79. }
  80. }