Amb.cs 11 KB

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