Amb.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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 = new CancellationTokenSource();
  29. var secondCancelToken = new CancellationTokenSource();
  30. //
  31. // The incoming cancellationToken should still be able to cancel both
  32. //
  33. var bothRegistry = cancellationToken.Register(() =>
  34. {
  35. firstCancelToken.Cancel();
  36. secondCancelToken.Cancel();
  37. });
  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. // NB: AwaitMoveNextAsyncAndDispose checks for null for both arguments, reducing the need for many null
  58. // checks over here.
  59. var cleanup = new[]
  60. {
  61. AwaitMoveNextAsyncAndDispose(secondMoveNext, secondEnumerator),
  62. AwaitMoveNextAsyncAndDispose(firstMoveNext, firstEnumerator)
  63. };
  64. bothRegistry.Dispose();
  65. await Task.WhenAll(cleanup).ConfigureAwait(false);
  66. throw;
  67. }
  68. //
  69. // REVIEW: Consider using the WhenAny combinator defined for Merge in TaskExt, which would avoid the need
  70. // to convert to Task<bool> prior to calling Task.WhenAny.
  71. //
  72. var moveNextWinner = await Task.WhenAny(firstMoveNext, secondMoveNext).ConfigureAwait(false);
  73. //
  74. // REVIEW: An alternative option is to call DisposeAsync on the other and await it, but this has two drawbacks:
  75. //
  76. // 1. Concurrent DisposeAsync while a MoveNextAsync is in flight.
  77. // 2. The winner elected by Amb is blocked to yield results until the loser unblocks.
  78. //
  79. IAsyncEnumerator<TSource> winner;
  80. Task disposeLoser;
  81. if (moveNextWinner == firstMoveNext)
  82. {
  83. winner = firstEnumerator;
  84. secondCancelToken.Cancel();
  85. disposeLoser = AwaitMoveNextAsyncAndDispose(secondMoveNext, secondEnumerator);
  86. }
  87. else
  88. {
  89. winner = secondEnumerator;
  90. firstCancelToken.Cancel();
  91. disposeLoser = AwaitMoveNextAsyncAndDispose(firstMoveNext, firstEnumerator);
  92. }
  93. try
  94. {
  95. await using (winner.ConfigureAwait(false))
  96. {
  97. if (!await moveNextWinner.ConfigureAwait(false))
  98. {
  99. yield break;
  100. }
  101. yield return winner.Current;
  102. while (await winner.MoveNextAsync().ConfigureAwait(false))
  103. {
  104. yield return winner.Current;
  105. }
  106. }
  107. }
  108. finally
  109. {
  110. bothRegistry.Dispose();
  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. public static IAsyncEnumerable<TSource> Amb<TSource>(params IAsyncEnumerable<TSource>[] sources)
  126. {
  127. if (sources == null)
  128. throw Error.ArgumentNull(nameof(sources));
  129. return AsyncEnumerable.Create(Core);
  130. async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
  131. {
  132. //
  133. // REVIEW: See remarks on binary overload for changes compared to the original.
  134. //
  135. var n = sources.Length;
  136. var enumerators = new IAsyncEnumerator<TSource>[n];
  137. var moveNexts = new Task<bool>[n];
  138. var individualTokenSources = new CancellationTokenSource[n];
  139. for (var i = 0; i < n; i++)
  140. {
  141. individualTokenSources[i] = new CancellationTokenSource();
  142. }
  143. var allIndividualDispose = cancellationToken.Register(() =>
  144. {
  145. foreach (var tokenSource in individualTokenSources)
  146. {
  147. tokenSource.Cancel();
  148. }
  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 = 0; i < n; i++)
  163. {
  164. cleanup[i] = AwaitMoveNextAsyncAndDispose(moveNexts[i], enumerators[i]);
  165. individualTokenSources[i].Cancel();
  166. }
  167. await Task.WhenAll(cleanup).ConfigureAwait(false);
  168. allIndividualDispose.Dispose();
  169. throw;
  170. }
  171. var moveNextWinner = await Task.WhenAny(moveNexts).ConfigureAwait(false);
  172. //
  173. // NB: The use of IndexOf is fine. If task N completed by returning a ValueTask<bool>
  174. // which is equivalent to the task returned by task M (where M < N), AsTask may
  175. // return the same reference (e.g. due to caching of completed Boolean tasks). In
  176. // such a case, IndexOf will find task M rather than N in the array, but both have
  177. // an equivalent completion state (because they're reference equal). This only leads
  178. // to a left-bias in selection of sources, but given Amb's "ambiguous" nature, this
  179. // is acceptable.
  180. //
  181. var winnerIndex = Array.IndexOf(moveNexts, moveNextWinner);
  182. var winner = enumerators[winnerIndex];
  183. var loserCleanupTasks = new List<Task>(n - 1);
  184. for (var i = 0; i < n; i++)
  185. {
  186. if (i != winnerIndex)
  187. {
  188. individualTokenSources[i].Cancel();
  189. var loserCleanupTask = AwaitMoveNextAsyncAndDispose(moveNexts[i], enumerators[i]);
  190. loserCleanupTasks.Add(loserCleanupTask);
  191. }
  192. }
  193. var cleanupLosers = Task.WhenAll(loserCleanupTasks);
  194. try
  195. {
  196. await using (winner.ConfigureAwait(false))
  197. {
  198. if (!await moveNextWinner.ConfigureAwait(false))
  199. {
  200. yield break;
  201. }
  202. yield return winner.Current;
  203. while (await winner.MoveNextAsync().ConfigureAwait(false))
  204. {
  205. yield return winner.Current;
  206. }
  207. }
  208. }
  209. finally
  210. {
  211. allIndividualDispose.Dispose();
  212. await cleanupLosers.ConfigureAwait(false);
  213. }
  214. }
  215. }
  216. public static IAsyncEnumerable<TSource> Amb<TSource>(this IEnumerable<IAsyncEnumerable<TSource>> sources)
  217. {
  218. if (sources == null)
  219. throw Error.ArgumentNull(nameof(sources));
  220. return Amb(sources.ToArray());
  221. }
  222. private static async Task AwaitMoveNextAsyncAndDispose<T>(Task<bool>? moveNextAsync, IAsyncEnumerator<T>? enumerator)
  223. {
  224. if (enumerator != null)
  225. {
  226. await using (enumerator.ConfigureAwait(false))
  227. {
  228. if (moveNextAsync != null)
  229. {
  230. try
  231. {
  232. await moveNextAsync.ConfigureAwait(false);
  233. }
  234. catch (TaskCanceledException)
  235. {
  236. // ignored because of cancelling the non-winners
  237. }
  238. }
  239. }
  240. }
  241. }
  242. }
  243. }