ETTaskHelper.cs 3.0 KB

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