ToEnumerable.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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.Tasks;
  6. namespace System.Linq
  7. {
  8. public static partial class AsyncEnumerable
  9. {
  10. // REVIEW: This type of blocking is an anti-pattern. We may want to move it to System.Interactive.Async
  11. // and remove it from System.Linq.Async API surface.
  12. /// <summary>
  13. /// Converts an async-enumerable sequence to an enumerable sequence.
  14. /// </summary>
  15. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  16. /// <param name="source">An async-enumerable sequence to convert to an enumerable sequence.</param>
  17. /// <returns>The enumerable sequence containing the elements in the async-enumerable sequence.</returns>
  18. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  19. public static IEnumerable<TSource> ToEnumerable<TSource>(this IAsyncEnumerable<TSource> source)
  20. {
  21. if (source == null)
  22. throw Error.ArgumentNull(nameof(source));
  23. return Core(source);
  24. static IEnumerable<TSource> Core(IAsyncEnumerable<TSource> source)
  25. {
  26. var e = source.GetAsyncEnumerator(default);
  27. try
  28. {
  29. while (true)
  30. {
  31. if (!Wait(e.MoveNextAsync()))
  32. break;
  33. yield return e.Current;
  34. }
  35. }
  36. finally
  37. {
  38. Wait(e.DisposeAsync());
  39. }
  40. }
  41. }
  42. // NB: ValueTask and ValueTask<T> do not have to support blocking on a call to GetResult when backed by
  43. // an IValueTaskSource or IValueTaskSource<T> implementation. Convert to a Task or Task<T> to do so
  44. // in case the task hasn't completed yet.
  45. private static void Wait(ValueTask task)
  46. {
  47. var awaiter = task.GetAwaiter();
  48. if (!awaiter.IsCompleted)
  49. {
  50. task.AsTask().GetAwaiter().GetResult();
  51. return;
  52. }
  53. awaiter.GetResult();
  54. }
  55. private static T Wait<T>(ValueTask<T> task)
  56. {
  57. var awaiter = task.GetAwaiter();
  58. if (!awaiter.IsCompleted)
  59. {
  60. return task.AsTask().GetAwaiter().GetResult();
  61. }
  62. return awaiter.GetResult();
  63. }
  64. }
  65. }