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 AsyncEnumerableEx
  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 async ValueTask DisposeAsync()
  34. {
  35. if (enumerator != null)
  36. {
  37. await enumerator.DisposeAsync().ConfigureAwait(false);
  38. enumerator = null;
  39. }
  40. await base.DisposeAsync().ConfigureAwait(false);
  41. }
  42. protected override async ValueTask<bool> MoveNextCore(CancellationToken cancellationToken)
  43. {
  44. switch (state)
  45. {
  46. case AsyncIteratorState.Allocated:
  47. enumerator = source.GetAsyncEnumerator(cancellationToken);
  48. state = AsyncIteratorState.Iterating;
  49. goto case AsyncIteratorState.Iterating;
  50. case AsyncIteratorState.Iterating:
  51. while (await enumerator.MoveNextAsync().ConfigureAwait(false))
  52. {
  53. }
  54. break; // case
  55. }
  56. await DisposeAsync().ConfigureAwait(false);
  57. return false;
  58. }
  59. }
  60. }
  61. }