Amb.cs 8.6 KB

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