IgnoreElements.cs 2.4 KB

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