Amb.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Threading.Tasks;
  7. namespace System.Linq
  8. {
  9. public static partial class AsyncEnumerableEx
  10. {
  11. public static IAsyncEnumerable<TSource> Amb<TSource>(this IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second)
  12. {
  13. if (first == null)
  14. throw new ArgumentNullException(nameof(first));
  15. if (second == null)
  16. throw new ArgumentNullException(nameof(second));
  17. return new AmbAsyncIterator<TSource>(first, second);
  18. }
  19. public static IAsyncEnumerable<TSource> Amb<TSource>(params IAsyncEnumerable<TSource>[] sources)
  20. {
  21. if (sources == null)
  22. throw new ArgumentNullException(nameof(sources));
  23. return new AmbAsyncIteratorN<TSource>(sources);
  24. }
  25. public static IAsyncEnumerable<TSource> Amb<TSource>(this IEnumerable<IAsyncEnumerable<TSource>> sources)
  26. {
  27. if (sources == null)
  28. throw new ArgumentNullException(nameof(sources));
  29. return new AmbAsyncIteratorN<TSource>(sources.ToArray());
  30. }
  31. private sealed class AmbAsyncIterator<TSource> : AsyncIterator<TSource>
  32. {
  33. private readonly IAsyncEnumerable<TSource> first;
  34. private readonly IAsyncEnumerable<TSource> second;
  35. private IAsyncEnumerator<TSource> enumerator;
  36. public AmbAsyncIterator(IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second)
  37. {
  38. Debug.Assert(first != null);
  39. Debug.Assert(second != null);
  40. this.first = first;
  41. this.second = second;
  42. }
  43. public override AsyncIterator<TSource> Clone()
  44. {
  45. return new AmbAsyncIterator<TSource>(first, second);
  46. }
  47. public override async Task DisposeAsync()
  48. {
  49. if (enumerator != null)
  50. {
  51. await enumerator.DisposeAsync().ConfigureAwait(false);
  52. enumerator = null;
  53. }
  54. await base.DisposeAsync().ConfigureAwait(false);
  55. }
  56. protected override async Task<bool> MoveNextCore()
  57. {
  58. switch (state)
  59. {
  60. case AsyncIteratorState.Allocated:
  61. var firstEnumerator = first.GetAsyncEnumerator();
  62. var secondEnumerator = second.GetAsyncEnumerator();
  63. var firstMoveNext = firstEnumerator.MoveNextAsync();
  64. var secondMoveNext = secondEnumerator.MoveNextAsync();
  65. var winner = await Task.WhenAny(firstMoveNext, secondMoveNext).ConfigureAwait(false);
  66. //
  67. // REVIEW: An alternative option is to call DisposeAsync on the other and await it, but this has two drawbacks:
  68. //
  69. // 1. Concurrent DisposeAsync while a MoveNextAsync is in flight.
  70. // 2. The winner elected by Amb is blocked to yield results until the loser unblocks.
  71. //
  72. // The approach below has one drawback, namely that exceptions raised by loser are dropped on the floor.
  73. //
  74. if (winner == firstMoveNext)
  75. {
  76. enumerator = firstEnumerator;
  77. var ignored = secondMoveNext.ContinueWith(_ =>
  78. {
  79. secondEnumerator.DisposeAsync();
  80. });
  81. }
  82. else
  83. {
  84. enumerator = secondEnumerator;
  85. var ignored = firstMoveNext.ContinueWith(_ =>
  86. {
  87. firstEnumerator.DisposeAsync();
  88. });
  89. }
  90. state = AsyncIteratorState.Iterating;
  91. if (await winner.ConfigureAwait(false))
  92. {
  93. current = enumerator.Current;
  94. return true;
  95. }
  96. break;
  97. case AsyncIteratorState.Iterating:
  98. if (await enumerator.MoveNextAsync().ConfigureAwait(false))
  99. {
  100. current = enumerator.Current;
  101. return true;
  102. }
  103. break;
  104. }
  105. await DisposeAsync().ConfigureAwait(false);
  106. return false;
  107. }
  108. }
  109. private sealed class AmbAsyncIteratorN<TSource> : AsyncIterator<TSource>
  110. {
  111. private readonly IAsyncEnumerable<TSource>[] sources;
  112. private IAsyncEnumerator<TSource> enumerator;
  113. public AmbAsyncIteratorN(IAsyncEnumerable<TSource>[] sources)
  114. {
  115. Debug.Assert(sources != null);
  116. this.sources = sources;
  117. }
  118. public override AsyncIterator<TSource> Clone()
  119. {
  120. return new AmbAsyncIteratorN<TSource>(sources);
  121. }
  122. public override async Task DisposeAsync()
  123. {
  124. if (enumerator != null)
  125. {
  126. await enumerator.DisposeAsync().ConfigureAwait(false);
  127. enumerator = null;
  128. }
  129. await base.DisposeAsync().ConfigureAwait(false);
  130. }
  131. protected override async Task<bool> MoveNextCore()
  132. {
  133. switch (state)
  134. {
  135. case AsyncIteratorState.Allocated:
  136. var n = sources.Length;
  137. var enumerators = new IAsyncEnumerator<TSource>[n];
  138. var moveNexts = new Task<bool>[n];
  139. for (var i = 0; i < n; i++)
  140. {
  141. var enumerator = sources[i].GetAsyncEnumerator();
  142. enumerators[i] = enumerator;
  143. moveNexts[i] = enumerator.MoveNextAsync();
  144. }
  145. var winner = await Task.WhenAny(moveNexts).ConfigureAwait(false);
  146. //
  147. // REVIEW: An alternative option is to call DisposeAsync on the other and await it, but this has two drawbacks:
  148. //
  149. // 1. Concurrent DisposeAsync while a MoveNextAsync is in flight.
  150. // 2. The winner elected by Amb is blocked to yield results until all losers unblocks.
  151. //
  152. // The approach below has one drawback, namely that exceptions raised by any loser are dropped on the floor.
  153. //
  154. var winnerIndex = Array.IndexOf(moveNexts, winner);
  155. enumerator = enumerators[winnerIndex];
  156. for (var i = 0; i < n; i++)
  157. {
  158. if (i != winnerIndex)
  159. {
  160. var ignored = moveNexts[i].ContinueWith(_ =>
  161. {
  162. enumerators[i].DisposeAsync();
  163. });
  164. }
  165. }
  166. state = AsyncIteratorState.Iterating;
  167. if (await winner.ConfigureAwait(false))
  168. {
  169. current = enumerator.Current;
  170. return true;
  171. }
  172. break;
  173. case AsyncIteratorState.Iterating:
  174. if (await enumerator.MoveNextAsync().ConfigureAwait(false))
  175. {
  176. current = enumerator.Current;
  177. return true;
  178. }
  179. break;
  180. }
  181. await DisposeAsync().ConfigureAwait(false);
  182. return false;
  183. }
  184. }
  185. }
  186. }