ToList.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. if (source is IAsyncIListProvider<TSource> listProvider)
  16. return listProvider.ToListAsync(cancellationToken).AsTask();
  17. return Core(source, cancellationToken);
  18. static async Task<List<TSource>> Core(IAsyncEnumerable<TSource> _source, CancellationToken _cancellationToken)
  19. {
  20. var list = new List<TSource>();
  21. #if CSHARP8
  22. await foreach (TSource item in _source.WithCancellation(_cancellationToken).ConfigureAwait(false))
  23. {
  24. list.Add(item);
  25. }
  26. #else
  27. var e = _source.GetAsyncEnumerator(_cancellationToken);
  28. try
  29. {
  30. while (await e.MoveNextAsync().ConfigureAwait(false))
  31. {
  32. list.Add(e.Current);
  33. }
  34. }
  35. finally
  36. {
  37. await e.DisposeAsync().ConfigureAwait(false);
  38. }
  39. #endif
  40. return list;
  41. }
  42. }
  43. }
  44. }