1
0

Take.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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.Diagnostics;
  6. using System.Threading.Tasks;
  7. namespace System.Linq
  8. {
  9. public static partial class AsyncEnumerable
  10. {
  11. public static IAsyncEnumerable<TSource> Take<TSource>(this IAsyncEnumerable<TSource> source, int count)
  12. {
  13. if (source == null)
  14. throw new ArgumentNullException(nameof(source));
  15. if (count <= 0)
  16. {
  17. return Empty<TSource>();
  18. }
  19. else if (source is IAsyncPartition<TSource> partition)
  20. {
  21. return partition.Take(count);
  22. }
  23. return new TakeAsyncIterator<TSource>(source, count);
  24. }
  25. private sealed class TakeAsyncIterator<TSource> : AsyncIterator<TSource>
  26. {
  27. private readonly int count;
  28. private readonly IAsyncEnumerable<TSource> source;
  29. private int currentCount;
  30. private IAsyncEnumerator<TSource> enumerator;
  31. public TakeAsyncIterator(IAsyncEnumerable<TSource> source, int count)
  32. {
  33. Debug.Assert(source != null);
  34. this.source = source;
  35. this.count = count;
  36. currentCount = count;
  37. }
  38. public override AsyncIterator<TSource> Clone()
  39. {
  40. return new TakeAsyncIterator<TSource>(source, count);
  41. }
  42. public override async Task DisposeAsync()
  43. {
  44. if (enumerator != null)
  45. {
  46. await enumerator.DisposeAsync().ConfigureAwait(false);
  47. enumerator = null;
  48. }
  49. await base.DisposeAsync().ConfigureAwait(false);
  50. }
  51. protected override async Task<bool> MoveNextCore()
  52. {
  53. switch (state)
  54. {
  55. case AsyncIteratorState.Allocated:
  56. enumerator = source.GetAsyncEnumerator();
  57. state = AsyncIteratorState.Iterating;
  58. goto case AsyncIteratorState.Iterating;
  59. case AsyncIteratorState.Iterating:
  60. if (currentCount > 0 && await enumerator.MoveNextAsync().ConfigureAwait(false))
  61. {
  62. current = enumerator.Current;
  63. currentCount--;
  64. return true;
  65. }
  66. break;
  67. }
  68. await DisposeAsync().ConfigureAwait(false);
  69. return false;
  70. }
  71. }
  72. }
  73. }