Amb.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace System.Linq
  8. {
  9. public static partial class AsyncEnumerableEx
  10. {
  11. /// <summary>
  12. /// Propagates the async-enumerable sequence that reacts first.
  13. /// </summary>
  14. /// <typeparam name="TSource">The type of the elements in the source sequences.</typeparam>
  15. /// <param name="first">First async-enumerable sequence.</param>
  16. /// <param name="second">Second async-enumerable sequence.</param>
  17. /// <returns>An async-enumerable sequence that surfaces either of the given sequences, whichever reacted first.</returns>
  18. /// <exception cref="ArgumentNullException"><paramref name="first"/> or <paramref name="second"/> is null.</exception>
  19. public static IAsyncEnumerable<TSource> Amb<TSource>(this IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second)
  20. {
  21. if (first == null)
  22. throw Error.ArgumentNull(nameof(first));
  23. if (second == null)
  24. throw Error.ArgumentNull(nameof(second));
  25. return Core(first, second);
  26. static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
  27. {
  28. IAsyncEnumerator<TSource>? firstEnumerator = null;
  29. IAsyncEnumerator<TSource>? secondEnumerator = null;
  30. Task<bool>? firstMoveNext = null;
  31. Task<bool>? secondMoveNext = null;
  32. //
  33. // We need separate tokens for each source so that the non-winner can get disposed and unblocked
  34. // i.e., see Never()
  35. //
  36. var firstCancelToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
  37. var secondCancelToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
  38. try
  39. {
  40. //
  41. // REVIEW: We start both sequences unconditionally. An alternative implementation could be to just stick
  42. // to the first sequence if we notice it already has a value (or exception) available. This would
  43. // be similar to Task.WhenAny behavior (see CommonCWAnyLogic in dotnet/coreclr). We could consider
  44. // adding a WhenAny combinator that does exactly that. We can even avoid calling AsTask.
  45. //
  46. firstEnumerator = first.GetAsyncEnumerator(firstCancelToken.Token);
  47. firstMoveNext = firstEnumerator.MoveNextAsync().AsTask();
  48. //
  49. // REVIEW: Order of operations has changed here compared to the original, but is now in sync with the N-ary
  50. // overload which performs GetAsyncEnumerator/MoveNextAsync in pairs, rather than phased.
  51. //
  52. secondEnumerator = second.GetAsyncEnumerator(secondCancelToken.Token);
  53. secondMoveNext = secondEnumerator.MoveNextAsync().AsTask();
  54. }
  55. catch
  56. {
  57. secondCancelToken.Cancel();
  58. firstCancelToken.Cancel();
  59. // NB: AwaitMoveNextAsyncAndDispose checks for null for both arguments, reducing the need for many null
  60. // checks over here.
  61. var cleanup = new[]
  62. {
  63. AwaitMoveNextAsyncAndDispose(secondMoveNext, secondEnumerator),
  64. AwaitMoveNextAsyncAndDispose(firstMoveNext, firstEnumerator)
  65. };
  66. await Task.WhenAll(cleanup).ConfigureAwait(false);
  67. throw;
  68. }
  69. //
  70. // REVIEW: Consider using the WhenAny combinator defined for Merge in TaskExt, which would avoid the need
  71. // to convert to Task<bool> prior to calling Task.WhenAny.
  72. //
  73. var moveNextWinner = await Task.WhenAny(firstMoveNext, secondMoveNext).ConfigureAwait(false);
  74. //
  75. // REVIEW: An alternative option is to call DisposeAsync on the other and await it, but this has two drawbacks:
  76. //
  77. // 1. Concurrent DisposeAsync while a MoveNextAsync is in flight.
  78. // 2. The winner elected by Amb is blocked to yield results until the loser unblocks.
  79. //
  80. IAsyncEnumerator<TSource> winner;
  81. Task disposeLoser;
  82. if (moveNextWinner == firstMoveNext)
  83. {
  84. winner = firstEnumerator;
  85. secondCancelToken.Cancel();
  86. disposeLoser = AwaitMoveNextAsyncAndDispose(secondMoveNext, secondEnumerator);
  87. }
  88. else
  89. {
  90. winner = secondEnumerator;
  91. firstCancelToken.Cancel();
  92. disposeLoser = AwaitMoveNextAsyncAndDispose(firstMoveNext, firstEnumerator);
  93. }
  94. try
  95. {
  96. await using (winner.ConfigureAwait(false))
  97. {
  98. if (!await moveNextWinner.ConfigureAwait(false))
  99. {
  100. yield break;
  101. }
  102. yield return winner.Current;
  103. while (await winner.MoveNextAsync().ConfigureAwait(false))
  104. {
  105. yield return winner.Current;
  106. }
  107. }
  108. }
  109. finally
  110. {
  111. //
  112. // REVIEW: This behavior differs from the original implementation in that we never discard any in flight
  113. // asynchronous operations. If an exception occurs while enumerating the winner, it can be
  114. // subsumed by an exception thrown due to cleanup of the loser. Also, if Amb is used to deal with
  115. // a potentially long-blocking sequence, this implementation would transfer this blocking behavior
  116. // to the resulting sequence. However, it seems never discarding a non-completed task should be a
  117. // general design tenet, and fire-and-forget dispose behavior could be added as another "unsafe"
  118. // operator, so all such sins are made explicit by the user. Nonetheless, this change is a breaking
  119. // change for Ix Async.
  120. //
  121. await disposeLoser.ConfigureAwait(false);
  122. }
  123. }
  124. }
  125. /// <summary>
  126. /// Propagates the async-enumerable sequence that reacts first.
  127. /// </summary>
  128. /// <typeparam name="TSource">The type of the elements in the source sequences.</typeparam>
  129. /// <param name="sources">Observable sources competing to react first.</param>
  130. /// <returns>An async-enumerable sequence that surfaces any of the given sequences, whichever reacted first.</returns>
  131. /// <exception cref="ArgumentNullException"><paramref name="sources"/> is null.</exception>
  132. public static IAsyncEnumerable<TSource> Amb<TSource>(params IAsyncEnumerable<TSource>[] sources)
  133. {
  134. if (sources == null)
  135. throw Error.ArgumentNull(nameof(sources));
  136. return AsyncEnumerable.Create(Core);
  137. async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
  138. {
  139. //
  140. // REVIEW: See remarks on binary overload for changes compared to the original.
  141. //
  142. var n = sources.Length;
  143. var enumerators = new IAsyncEnumerator<TSource>[n];
  144. var moveNexts = new Task<bool>[n];
  145. var individualTokenSources = new CancellationTokenSource[n];
  146. for (var i = 0; i < n; i++)
  147. {
  148. individualTokenSources[i] = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
  149. }
  150. try
  151. {
  152. for (var i = 0; i < n; i++)
  153. {
  154. var enumerator = sources[i].GetAsyncEnumerator(individualTokenSources[i].Token);
  155. enumerators[i] = enumerator;
  156. moveNexts[i] = enumerator.MoveNextAsync().AsTask();
  157. }
  158. }
  159. catch
  160. {
  161. var cleanup = new Task[n];
  162. for (var i = n - 1; i >= 0; i--)
  163. {
  164. individualTokenSources[i].Cancel();
  165. cleanup[i] = AwaitMoveNextAsyncAndDispose(moveNexts[i], enumerators[i]);
  166. }
  167. await Task.WhenAll(cleanup).ConfigureAwait(false);
  168. throw;
  169. }
  170. var moveNextWinner = await Task.WhenAny(moveNexts).ConfigureAwait(false);
  171. //
  172. // NB: The use of IndexOf is fine. If task N completed by returning a ValueTask<bool>
  173. // which is equivalent to the task returned by task M (where M < N), AsTask may
  174. // return the same reference (e.g. due to caching of completed Boolean tasks). In
  175. // such a case, IndexOf will find task M rather than N in the array, but both have
  176. // an equivalent completion state (because they're reference equal). This only leads
  177. // to a left-bias in selection of sources, but given Amb's "ambiguous" nature, this
  178. // is acceptable.
  179. //
  180. var winnerIndex = Array.IndexOf(moveNexts, moveNextWinner);
  181. var winner = enumerators[winnerIndex];
  182. var loserCleanupTasks = new List<Task>(n - 1);
  183. for (var i = n - 1; i >= 0; i--)
  184. {
  185. if (i != winnerIndex)
  186. {
  187. individualTokenSources[i].Cancel();
  188. var loserCleanupTask = AwaitMoveNextAsyncAndDispose(moveNexts[i], enumerators[i]);
  189. loserCleanupTasks.Add(loserCleanupTask);
  190. }
  191. }
  192. var cleanupLosers = Task.WhenAll(loserCleanupTasks);
  193. try
  194. {
  195. await using (winner.ConfigureAwait(false))
  196. {
  197. if (!await moveNextWinner.ConfigureAwait(false))
  198. {
  199. yield break;
  200. }
  201. yield return winner.Current;
  202. while (await winner.MoveNextAsync().ConfigureAwait(false))
  203. {
  204. yield return winner.Current;
  205. }
  206. }
  207. }
  208. finally
  209. {
  210. await cleanupLosers.ConfigureAwait(false);
  211. }
  212. }
  213. }
  214. /// <summary>
  215. /// Propagates the async-enumerable sequence that reacts first.
  216. /// </summary>
  217. /// <typeparam name="TSource">The type of the elements in the source sequences.</typeparam>
  218. /// <param name="sources">Observable sources competing to react first.</param>
  219. /// <returns>An async-enumerable sequence that surfaces any of the given sequences, whichever reacted first.</returns>
  220. /// <exception cref="ArgumentNullException"><paramref name="sources"/> is null.</exception>
  221. public static IAsyncEnumerable<TSource> Amb<TSource>(this IEnumerable<IAsyncEnumerable<TSource>> sources)
  222. {
  223. if (sources == null)
  224. throw Error.ArgumentNull(nameof(sources));
  225. return Amb(sources.ToArray());
  226. }
  227. private static async Task AwaitMoveNextAsyncAndDispose<T>(Task<bool>? moveNextAsync, IAsyncEnumerator<T>? enumerator)
  228. {
  229. if (enumerator != null)
  230. {
  231. await using (enumerator.ConfigureAwait(false))
  232. {
  233. if (moveNextAsync != null)
  234. {
  235. try
  236. {
  237. await moveNextAsync.ConfigureAwait(false);
  238. }
  239. catch (TaskCanceledException)
  240. {
  241. // ignored because of cancelling the non-winners
  242. }
  243. }
  244. }
  245. }
  246. }
  247. }
  248. }