IgnoreElements.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace System.Linq
  10. {
  11. public static partial class AsyncEnumerable
  12. {
  13. public static IAsyncEnumerable<TSource> IgnoreElements<TSource>(this IAsyncEnumerable<TSource> source)
  14. {
  15. if (source == null)
  16. throw new ArgumentNullException(nameof(source));
  17. return new IgnoreElementsAsyncIterator<TSource>(source);
  18. }
  19. private sealed class IgnoreElementsAsyncIterator<TSource> : AsyncIterator<TSource>
  20. {
  21. private readonly IAsyncEnumerable<TSource> source;
  22. private IAsyncEnumerator<TSource> enumerator;
  23. public IgnoreElementsAsyncIterator(IAsyncEnumerable<TSource> source)
  24. {
  25. this.source = source;
  26. }
  27. public override AsyncIterator<TSource> Clone()
  28. {
  29. return new IgnoreElementsAsyncIterator<TSource>(source);
  30. }
  31. public override void Dispose()
  32. {
  33. if (enumerator != null)
  34. {
  35. enumerator.Dispose();
  36. enumerator = null;
  37. }
  38. base.Dispose();
  39. }
  40. protected override async Task<bool> MoveNextCore(CancellationToken cancellationToken)
  41. {
  42. switch (state)
  43. {
  44. case AsyncIteratorState.Allocated:
  45. enumerator = source.GetEnumerator();
  46. state = AsyncIteratorState.Iterating;
  47. goto case AsyncIteratorState.Iterating;
  48. case AsyncIteratorState.Iterating:
  49. while (await enumerator.MoveNext(cancellationToken)
  50. .ConfigureAwait(false))
  51. {
  52. // Do nothing, we're ignoring these elements
  53. }
  54. break; // case
  55. }
  56. Dispose();
  57. return false;
  58. }
  59. }
  60. }
  61. }