Take.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. return new TakeAsyncIterator<TSource>(source, count);
  20. }
  21. private sealed class TakeAsyncIterator<TSource> : AsyncIterator<TSource>
  22. {
  23. private readonly int count;
  24. private readonly IAsyncEnumerable<TSource> source;
  25. private int currentCount;
  26. private IAsyncEnumerator<TSource> enumerator;
  27. public TakeAsyncIterator(IAsyncEnumerable<TSource> source, int count)
  28. {
  29. Debug.Assert(source != null);
  30. this.source = source;
  31. this.count = count;
  32. currentCount = count;
  33. }
  34. public override AsyncIterator<TSource> Clone()
  35. {
  36. return new TakeAsyncIterator<TSource>(source, count);
  37. }
  38. public override async Task DisposeAsync()
  39. {
  40. if (enumerator != null)
  41. {
  42. await enumerator.DisposeAsync().ConfigureAwait(false);
  43. enumerator = null;
  44. }
  45. await base.DisposeAsync().ConfigureAwait(false);
  46. }
  47. protected override async Task<bool> MoveNextCore()
  48. {
  49. switch (state)
  50. {
  51. case AsyncIteratorState.Allocated:
  52. enumerator = source.GetAsyncEnumerator();
  53. state = AsyncIteratorState.Iterating;
  54. goto case AsyncIteratorState.Iterating;
  55. case AsyncIteratorState.Iterating:
  56. if (currentCount > 0 && await enumerator.MoveNextAsync().ConfigureAwait(false))
  57. {
  58. current = enumerator.Current;
  59. currentCount--;
  60. return true;
  61. }
  62. break;
  63. }
  64. await DisposeAsync().ConfigureAwait(false);
  65. return false;
  66. }
  67. }
  68. }
  69. }