ToEnumerable.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. namespace System.Linq
  6. {
  7. public static partial class AsyncEnumerable
  8. {
  9. public static IEnumerable<TSource> ToEnumerable<TSource>(this IAsyncEnumerable<TSource> source)
  10. {
  11. if (source == null)
  12. throw new ArgumentNullException(nameof(source));
  13. return ToEnumerableCore(source);
  14. }
  15. private static IEnumerable<TSource> ToEnumerableCore<TSource>(IAsyncEnumerable<TSource> source)
  16. {
  17. var e = source.GetAsyncEnumerator(default);
  18. try
  19. {
  20. while (true)
  21. {
  22. if (!e.MoveNextAsync().Result)
  23. break;
  24. var c = e.Current;
  25. yield return c;
  26. }
  27. }
  28. finally
  29. {
  30. // Wait
  31. e.DisposeAsync().GetAwaiter().GetResult();
  32. }
  33. }
  34. }
  35. }