Merge.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. /// <summary>
  12. /// Merges elements from all of the specified observable sequences into a single observable sequence.
  13. /// </summary>
  14. /// <typeparam name="TSource">The type of the elements in the source sequences.</typeparam>
  15. /// <param name="sources">Observable sequences.</param>
  16. /// <returns>The observable sequence that merges the elements of the observable 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. #if USE_FAIR_AND_CHEAPER_MERGE
  23. //
  24. // This new implementation of Merge differs from the original one in a few ways:
  25. //
  26. // - It's cheaper because:
  27. // - no conversion from ValueTask<bool> to Task<bool> takes place using AsTask,
  28. // - we don't instantiate Task.WhenAny tasks for each iteration.
  29. // - It's fairer because:
  30. // - the MoveNextAsync tasks are awaited concurently, but completions are queued,
  31. // instead of awaiting a new WhenAny task where "left" sources have preferential
  32. // treatment over "right" sources.
  33. //
  34. return AsyncEnumerable.Create(Core);
  35. async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
  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. return AsyncEnumerable.Create(Core);
  151. async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
  152. {
  153. var count = sources.Length;
  154. var enumerators = new IAsyncEnumerator<TSource>?[count];
  155. var moveNextTasks = new Task<bool>[count];
  156. try
  157. {
  158. for (var i = 0; i < count; i++)
  159. {
  160. var enumerator = sources[i].GetAsyncEnumerator(cancellationToken);
  161. enumerators[i] = enumerator;
  162. // REVIEW: This follows the lead of the original implementation where we kick off MoveNextAsync
  163. // operations immediately. An alternative would be to do this in a separate stage, thus
  164. // preventing concurrency across MoveNextAsync and GetAsyncEnumerator calls and avoiding
  165. // any MoveNextAsync calls before all enumerators are acquired (or an exception has
  166. // occurred doing so).
  167. moveNextTasks[i] = enumerator.MoveNextAsync().AsTask();
  168. }
  169. var active = count;
  170. while (active > 0)
  171. {
  172. // REVIEW: Performance of WhenAny may be an issue when called repeatedly like this. We should
  173. // measure and could consider operating directly on the ValueTask<bool> objects, thus
  174. // also preventing the Task<bool> allocations from AsTask.
  175. var moveNextTask = await Task.WhenAny(moveNextTasks).ConfigureAwait(false);
  176. // REVIEW: This seems wrong. AsTask can return the original Task<bool> (if the ValueTask<bool>
  177. // is wrapping one) or return a singleton instance for true and false, at which point
  178. // the use of IndexOf may pick an element closer to the start of the array because of
  179. // reference equality checks and aliasing effects. See GetTaskForResult in the BCL.
  180. var index = Array.IndexOf(moveNextTasks, moveNextTask);
  181. var enumerator = enumerators[index]!; // NB: Only gets set to null after setting task to Never.
  182. if (!await moveNextTask.ConfigureAwait(false))
  183. {
  184. moveNextTasks[index] = TaskExt.Never;
  185. // REVIEW: The original implementation did not dispose eagerly, which could lead to resource
  186. // leaks when merged with other long-running sequences.
  187. enumerators[index] = null; // NB: Avoids attempt at double dispose in finally if disposing fails.
  188. await enumerator.DisposeAsync().ConfigureAwait(false);
  189. active--;
  190. }
  191. else
  192. {
  193. var item = enumerator.Current;
  194. moveNextTasks[index] = enumerator.MoveNextAsync().AsTask();
  195. yield return item;
  196. }
  197. }
  198. }
  199. finally
  200. {
  201. // REVIEW: The original implementation performs a concurrent dispose, which seems undesirable given the
  202. // additional uncontrollable source of concurrency and the sequential resource acquisition. In
  203. // this modern implementation, we release resources in opposite order as we acquired them, thus
  204. // guaranteeing determinism (and mimicking a series of nested `await using` statements).
  205. // REVIEW: If we decide to phase GetAsyncEnumerator and the initial MoveNextAsync calls at the start of
  206. // the operator implementation, we should make this symmetric and first await all in flight
  207. // MoveNextAsync operations, prior to disposing the enumerators.
  208. var errors = default(List<Exception>);
  209. for (var i = count - 1; i >= 0; i--)
  210. {
  211. var moveNextTask = moveNextTasks[i];
  212. var enumerator = enumerators[i];
  213. try
  214. {
  215. try
  216. {
  217. if (moveNextTask != null && moveNextTask != TaskExt.Never)
  218. {
  219. _ = await moveNextTask.ConfigureAwait(false);
  220. }
  221. }
  222. finally
  223. {
  224. if (enumerator != null)
  225. {
  226. await enumerator.DisposeAsync().ConfigureAwait(false);
  227. }
  228. }
  229. }
  230. catch (Exception ex)
  231. {
  232. if (errors == null)
  233. {
  234. errors = new List<Exception>();
  235. }
  236. errors.Add(ex);
  237. }
  238. }
  239. // NB: If we had any errors during cleaning (and awaiting pending operations), we throw these exceptions
  240. // instead of the original exception that may have led to running the finally block. This is similar
  241. // to throwing from any finally block (except that we catch all exceptions to ensure cleanup of all
  242. // concurrent sequences being merged).
  243. if (errors != null)
  244. {
  245. throw new AggregateException(errors);
  246. }
  247. }
  248. }
  249. #endif
  250. }
  251. /// <summary>
  252. /// Merges elements from all observable sequences in the given enumerable sequence into a single observable sequence.
  253. /// </summary>
  254. /// <typeparam name="TSource">The type of the elements in the source sequences.</typeparam>
  255. /// <param name="sources">Enumerable sequence of observable sequences.</param>
  256. /// <returns>The observable sequence that merges the elements of the observable 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 observable sequences into a single observable sequence.
  284. /// </summary>
  285. /// <typeparam name="TSource">The type of the elements in the source sequences.</typeparam>
  286. /// <param name="sources">Observable sequence of inner observable sequences.</param>
  287. /// <returns>The observable 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. }