IgnoreElements.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. throw new ArgumentNullException(nameof(source));
  16. return new IgnoreElementsAsyncIterator<TSource>(source);
  17. }
  18. private sealed class IgnoreElementsAsyncIterator<TSource> : AsyncIterator<TSource>
  19. {
  20. private readonly IAsyncEnumerable<TSource> source;
  21. private IAsyncEnumerator<TSource> enumerator;
  22. public IgnoreElementsAsyncIterator(IAsyncEnumerable<TSource> source)
  23. {
  24. Debug.Assert(source != null);
  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. }