Merge.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. /// Merges elements from all of the specified async-enumerable sequences into a single async-enumerable sequence.
  13. /// </summary>
  14. /// <typeparam name="TSource">The type of the elements in the source sequences.</typeparam>
  15. /// <param name="sources">Async-enumerable sequences.</param>
  16. /// <returns>The async-enumerable sequence that merges the elements of the async-enumerable sequences.</returns>
  17. /// <exception cref="ArgumentNullException"><paramref name="sources"/> is null.</exception>
  18. public static IAsyncEnumerable<TSource> Merge<TSource>(params IAsyncEnumerable<TSource>[] sources)
  19. {
  20. if (sources == null)
  21. throw Error.ArgumentNull(nameof(sources));
  22. return Core(sources);
  23. static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource>[] sources, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
  24. #if USE_FAIR_AND_CHEAPER_MERGE
  25. //
  26. // This new implementation of Merge differs from the original one in a few ways:
  27. //
  28. // - It's cheaper because:
  29. // - no conversion from ValueTask<bool> to Task<bool> takes place using AsTask,
  30. // - we don't instantiate Task.WhenAny tasks for each iteration.
  31. // - It's fairer because:
  32. // - the MoveNextAsync tasks are awaited concurently, but completions are queued,
  33. // instead of awaiting a new WhenAny task where "left" sources have preferential
  34. // treatment over "right" sources.
  35. //
  36. {
  37. var count = sources.Length;
  38. var enumerators = new IAsyncEnumerator<TSource>[count];
  39. var moveNextTasks = new ValueTask<bool>[count];
  40. try
  41. {
  42. for (var i = 0; i < count; i++)
  43. {
  44. IAsyncEnumerator<TSource> enumerator = sources[i].GetAsyncEnumerator(cancellationToken);
  45. enumerators[i] = enumerator;
  46. // REVIEW: This follows the lead of the original implementation where we kick off MoveNextAsync
  47. // operations immediately. An alternative would be to do this in a separate stage, thus
  48. // preventing concurrency across MoveNextAsync and GetAsyncEnumerator calls and avoiding
  49. // any MoveNextAsync calls before all enumerators are acquired (or an exception has
  50. // occurred doing so).
  51. moveNextTasks[i] = enumerator.MoveNextAsync();
  52. }
  53. var whenAny = TaskExt.WhenAny(moveNextTasks);
  54. int active = count;
  55. while (active > 0)
  56. {
  57. int index = await whenAny;
  58. IAsyncEnumerator<TSource> enumerator = enumerators[index];
  59. ValueTask<bool> moveNextTask = moveNextTasks[index];
  60. if (!await moveNextTask.ConfigureAwait(false))
  61. {
  62. //
  63. // Replace the task in our array by a completed task to make finally logic easier. Note that
  64. // the WhenAnyValueTask object has a reference to our array (i.e. no copy is made), so this
  65. // gets rid of any resources the original task may have held onto. However, we *don't* call
  66. // whenAny.Replace to set this value, because it'd attach an awaiter to the already completed
  67. // task, causing spurious wake-ups when awaiting whenAny.
  68. //
  69. moveNextTasks[index] = new ValueTask<bool>();
  70. // REVIEW: The original implementation did not dispose eagerly, which could lead to resource
  71. // leaks when merged with other long-running sequences.
  72. enumerators[index] = null; // NB: Avoids attempt at double dispose in finally if disposing fails.
  73. await enumerator.DisposeAsync().ConfigureAwait(false);
  74. active--;
  75. }
  76. else
  77. {
  78. TSource item = enumerator.Current;
  79. //
  80. // Replace the task using whenAny.Replace, which will write it to the moveNextTasks array, and
  81. // will start awaiting the task. Note we don't have to write to moveNextTasks ourselves because
  82. // the whenAny object has a reference to it (i.e. no copy is made).
  83. //
  84. whenAny.Replace(index, enumerator.MoveNextAsync());
  85. yield return item;
  86. }
  87. }
  88. }
  89. finally
  90. {
  91. // REVIEW: The original implementation performs a concurrent dispose, which seems undesirable given the
  92. // additional uncontrollable source of concurrency and the sequential resource acquisition. In
  93. // this modern implementation, we release resources in opposite order as we acquired them, thus
  94. // guaranteeing determinism (and mimicking a series of nested `await using` statements).
  95. // REVIEW: If we decide to phase GetAsyncEnumerator and the initial MoveNextAsync calls at the start of
  96. // the operator implementation, we should make this symmetric and first await all in flight
  97. // MoveNextAsync operations, prior to disposing the enumerators.
  98. var errors = default(List<Exception>);
  99. for (var i = count - 1; i >= 0; i--)
  100. {
  101. ValueTask<bool> moveNextTask = moveNextTasks[i];
  102. IAsyncEnumerator<TSource> enumerator = enumerators[i];
  103. try
  104. {
  105. try
  106. {
  107. //
  108. // Await the task to ensure outstanding work is completed prior to performing a dispose
  109. // operation. Note that we don't have to do anything special for tasks belonging to
  110. // enumerators that have finished; we swapped in a placeholder completed task.
  111. //
  112. // REVIEW: This adds an additional continuation to all of the pending tasks (note that
  113. // whenAny also has registered one). The whenAny object will be collectible
  114. // after all of these complete. Alternatively, we could drain via whenAny, by
  115. // awaiting it until the active count drops to 0. This saves on attaching the
  116. // additional continuations, but we need to decide on order of dispose. Right
  117. // now, we dispose in opposite order of acquiring the enumerators, with the
  118. // exception of enumerators that were disposed eagerly upon early completion.
  119. // Should we care about the dispose order at all?
  120. _ = await moveNextTask.ConfigureAwait(false);
  121. }
  122. finally
  123. {
  124. if (enumerator != null)
  125. {
  126. await enumerator.DisposeAsync().ConfigureAwait(false);
  127. }
  128. }
  129. }
  130. catch (Exception ex)
  131. {
  132. if (errors == null)
  133. {
  134. errors = new List<Exception>();
  135. }
  136. errors.Add(ex);
  137. }
  138. }
  139. // NB: If we had any errors during cleaning (and awaiting pending operations), we throw these exceptions
  140. // instead of the original exception that may have led to running the finally block. This is similar
  141. // to throwing from any finally block (except that we catch all exceptions to ensure cleanup of all
  142. // concurrent sequences being merged).
  143. if (errors != null)
  144. {
  145. throw new AggregateException(errors);
  146. }
  147. }
  148. }
  149. #else
  150. {
  151. var count = sources.Length;
  152. var enumerators = new IAsyncEnumerator<TSource>?[count];
  153. var moveNextTasks = new Task<bool>[count];
  154. try
  155. {
  156. for (var i = 0; i < count; i++)
  157. {
  158. var enumerator = sources[i].GetAsyncEnumerator(cancellationToken);
  159. enumerators[i] = enumerator;
  160. // REVIEW: This follows the lead of the original implementation where we kick off MoveNextAsync
  161. // operations immediately. An alternative would be to do this in a separate stage, thus
  162. // preventing concurrency across MoveNextAsync and GetAsyncEnumerator calls and avoiding
  163. // any MoveNextAsync calls before all enumerators are acquired (or an exception has
  164. // occurred doing so).
  165. moveNextTasks[i] = enumerator.MoveNextAsync().AsTask();
  166. }
  167. var active = count;
  168. while (active > 0)
  169. {
  170. // REVIEW: Performance of WhenAny may be an issue when called repeatedly like this. We should
  171. // measure and could consider operating directly on the ValueTask<bool> objects, thus
  172. // also preventing the Task<bool> allocations from AsTask.
  173. var moveNextTask = await Task.WhenAny(moveNextTasks).ConfigureAwait(false);
  174. // REVIEW: This seems wrong. AsTask can return the original Task<bool> (if the ValueTask<bool>
  175. // is wrapping one) or return a singleton instance for true and false, at which point
  176. // the use of IndexOf may pick an element closer to the start of the array because of
  177. // reference equality checks and aliasing effects. See GetTaskForResult in the BCL.
  178. var index = Array.IndexOf(moveNextTasks, moveNextTask);
  179. var enumerator = enumerators[index]!; // NB: Only gets set to null after setting task to Never.
  180. if (!await moveNextTask.ConfigureAwait(false))
  181. {
  182. moveNextTasks[index] = TaskExt.Never;
  183. // REVIEW: The original implementation did not dispose eagerly, which could lead to resource
  184. // leaks when merged with other long-running sequences.
  185. enumerators[index] = null; // NB: Avoids attempt at double dispose in finally if disposing fails.
  186. await enumerator.DisposeAsync().ConfigureAwait(false);
  187. active--;
  188. }
  189. else
  190. {
  191. var item = enumerator.Current;
  192. moveNextTasks[index] = enumerator.MoveNextAsync().AsTask();
  193. yield return item;
  194. }
  195. }
  196. }
  197. finally
  198. {
  199. // REVIEW: The original implementation performs a concurrent dispose, which seems undesirable given the
  200. // additional uncontrollable source of concurrency and the sequential resource acquisition. In
  201. // this modern implementation, we release resources in opposite order as we acquired them, thus
  202. // guaranteeing determinism (and mimicking a series of nested `await using` statements).
  203. // REVIEW: If we decide to phase GetAsyncEnumerator and the initial MoveNextAsync calls at the start of
  204. // the operator implementation, we should make this symmetric and first await all in flight
  205. // MoveNextAsync operations, prior to disposing the enumerators.
  206. var errors = default(List<Exception>);
  207. for (var i = count - 1; i >= 0; i--)
  208. {
  209. var moveNextTask = moveNextTasks[i];
  210. var enumerator = enumerators[i];
  211. try
  212. {
  213. try
  214. {
  215. if (moveNextTask != null && moveNextTask != TaskExt.Never)
  216. {
  217. _ = await moveNextTask.ConfigureAwait(false);
  218. }
  219. }
  220. finally
  221. {
  222. if (enumerator != null)
  223. {
  224. await enumerator.DisposeAsync().ConfigureAwait(false);
  225. }
  226. }
  227. }
  228. catch (Exception ex)
  229. {
  230. (errors ??= []).Add(ex);
  231. }
  232. }
  233. // NB: If we had any errors during cleaning (and awaiting pending operations), we throw these exceptions
  234. // instead of the original exception that may have led to running the finally block. This is similar
  235. // to throwing from any finally block (except that we catch all exceptions to ensure cleanup of all
  236. // concurrent sequences being merged).
  237. if (errors != null)
  238. {
  239. #if NET6_0_OR_GREATER
  240. #pragma warning disable CA2219 // Do not raise an exception from within a finally clause
  241. #endif
  242. throw new AggregateException(errors);
  243. #if NET6_0_OR_GREATER
  244. #pragma warning restore CA2219
  245. #endif
  246. }
  247. }
  248. }
  249. #endif
  250. }
  251. /// <summary>
  252. /// Merges elements from all async-enumerable sequences in the given enumerable sequence into a single async-enumerable sequence.
  253. /// </summary>
  254. /// <typeparam name="TSource">The type of the elements in the source sequences.</typeparam>
  255. /// <param name="sources">Enumerable sequence of async-enumerable sequences.</param>
  256. /// <returns>The async-enumerable sequence that merges the elements of the async-enumerable sequences.</returns>
  257. /// <exception cref="ArgumentNullException"><paramref name="sources"/> is null.</exception>
  258. public static IAsyncEnumerable<TSource> Merge<TSource>(this IEnumerable<IAsyncEnumerable<TSource>> sources)
  259. {
  260. if (sources == null)
  261. throw Error.ArgumentNull(nameof(sources));
  262. //
  263. // REVIEW: This implementation does not exploit concurrency. We should not introduce such behavior in order to
  264. // avoid breaking changes, but we could introduce a parallel ConcurrentMerge implementation. It is
  265. // unfortunate though that the Merge overload accepting an array has always been concurrent, so we can't
  266. // change that either (in order to have consistency where Merge is non-concurrent, and ConcurrentMerge
  267. // is). We could consider a breaking change to Ix Async to streamline this, but we should do so when
  268. // shipping with the BCL interfaces (which is already a breaking change to existing Ix Async users). If
  269. // we go that route, we can either have:
  270. //
  271. // - All overloads of Merge are concurrent
  272. // - and continue to be named Merge, or,
  273. // - are renamed to ConcurrentMerge for clarity (likely alongside a ConcurrentZip).
  274. // - All overloads of Merge are non-concurrent
  275. // - and are simply SelectMany operator macros (maybe more optimized)
  276. // - Have ConcurrentMerge next to Merge overloads
  277. // - where ConcurrentMerge may need a degree of concurrency parameter (and maybe other options), and,
  278. // - where the overload set of both families may be asymmetric
  279. //
  280. return sources.ToAsyncEnumerable().SelectMany(source => source);
  281. }
  282. /// <summary>
  283. /// Merges elements from all inner async-enumerable sequences into a single async-enumerable sequence.
  284. /// </summary>
  285. /// <typeparam name="TSource">The type of the elements in the source sequences.</typeparam>
  286. /// <param name="sources">Async-enumerable sequence of inner async-enumerable sequences.</param>
  287. /// <returns>The async-enumerable sequence that merges the elements of the inner sequences.</returns>
  288. /// <exception cref="ArgumentNullException"><paramref name="sources"/> is null.</exception>
  289. public static IAsyncEnumerable<TSource> Merge<TSource>(this IAsyncEnumerable<IAsyncEnumerable<TSource>> sources)
  290. {
  291. if (sources == null)
  292. throw Error.ArgumentNull(nameof(sources));
  293. //
  294. // REVIEW: This implementation does not exploit concurrency. We should not introduce such behavior in order to
  295. // avoid breaking changes, but we could introduce a parallel ConcurrentMerge implementation.
  296. //
  297. return sources.SelectMany(source => source);
  298. }
  299. }
  300. }