Amb.cs 13 KB

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