ToList.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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 AsyncEnumerable
  10. {
  11. public static Task<List<TSource>> ToListAsync<TSource>(this IAsyncEnumerable<TSource> source, CancellationToken cancellationToken = default)
  12. {
  13. if (source == null)
  14. throw Error.ArgumentNull(nameof(source));
  15. return ToListCore(source, cancellationToken);
  16. }
  17. private static Task<List<TSource>> ToListCore<TSource>(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  18. {
  19. if (source is IAsyncIListProvider<TSource> listProvider)
  20. return listProvider.ToListAsync(cancellationToken).AsTask();
  21. return Core();
  22. async Task<List<TSource>> Core()
  23. {
  24. var e = source.GetAsyncEnumerator(cancellationToken);
  25. try
  26. {
  27. var list = new List<TSource>();
  28. while (await e.MoveNextAsync().ConfigureAwait(false))
  29. {
  30. list.Add(e.Current);
  31. }
  32. return list;
  33. }
  34. finally
  35. {
  36. await e.DisposeAsync().ConfigureAwait(false);
  37. }
  38. }
  39. }
  40. }
  41. }