ETTaskHelper.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. using System;
  2. using System.Collections.Generic;
  3. namespace ET
  4. {
  5. public static class ETTaskHelper
  6. {
  7. public static bool IsCancel(this ETCancellationToken self)
  8. {
  9. if (self == null)
  10. {
  11. return false;
  12. }
  13. return self.IsDispose();
  14. }
  15. private class CoroutineBlocker
  16. {
  17. private int count;
  18. private ETTask tcs;
  19. public CoroutineBlocker(int count)
  20. {
  21. this.count = count;
  22. }
  23. public async ETTask RunSubCoroutineAsync(ETTask task)
  24. {
  25. try
  26. {
  27. await task;
  28. }
  29. finally
  30. {
  31. --this.count;
  32. if (this.count <= 0 && this.tcs != null)
  33. {
  34. ETTask t = this.tcs;
  35. this.tcs = null;
  36. t.SetResult();
  37. }
  38. }
  39. }
  40. public async ETTask WaitAsync()
  41. {
  42. if (this.count <= 0)
  43. {
  44. return;
  45. }
  46. this.tcs = ETTask.Create(true);
  47. await tcs;
  48. }
  49. }
  50. public static async ETTask WaitAny(List<ETTask> tasks)
  51. {
  52. if (tasks.Count == 0)
  53. {
  54. return;
  55. }
  56. CoroutineBlocker coroutineBlocker = new CoroutineBlocker(1);
  57. foreach (ETTask task in tasks)
  58. {
  59. coroutineBlocker.RunSubCoroutineAsync(task).Coroutine();
  60. }
  61. await coroutineBlocker.WaitAsync();
  62. }
  63. public static async ETTask WaitAny(ETTask[] tasks)
  64. {
  65. if (tasks.Length == 0)
  66. {
  67. return;
  68. }
  69. CoroutineBlocker coroutineBlocker = new CoroutineBlocker(1);
  70. foreach (ETTask task in tasks)
  71. {
  72. coroutineBlocker.RunSubCoroutineAsync(task).Coroutine();
  73. }
  74. await coroutineBlocker.WaitAsync();
  75. }
  76. public static async ETTask WaitAll(ETTask[] tasks)
  77. {
  78. if (tasks.Length == 0)
  79. {
  80. return;
  81. }
  82. CoroutineBlocker coroutineBlocker = new CoroutineBlocker(tasks.Length);
  83. foreach (ETTask task in tasks)
  84. {
  85. coroutineBlocker.RunSubCoroutineAsync(task).Coroutine();
  86. }
  87. await coroutineBlocker.WaitAsync();
  88. }
  89. public static async ETTask WaitAll(List<ETTask> tasks)
  90. {
  91. if (tasks.Count == 0)
  92. {
  93. return;
  94. }
  95. CoroutineBlocker coroutineBlocker = new CoroutineBlocker(tasks.Count);
  96. foreach (ETTask task in tasks)
  97. {
  98. coroutineBlocker.RunSubCoroutineAsync(task).Coroutine();
  99. }
  100. await coroutineBlocker.WaitAsync();
  101. }
  102. }
  103. }