IgnoreElements.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. throw Error.ArgumentNull(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. _source = source;
  26. }
  27. public override AsyncIteratorBase<TSource> Clone()
  28. {
  29. return new IgnoreElementsAsyncIterator<TSource>(_source);
  30. }
  31. public override async ValueTask DisposeAsync()
  32. {
  33. if (_enumerator != null)
  34. {
  35. await _enumerator.DisposeAsync().ConfigureAwait(false);
  36. _enumerator = null;
  37. }
  38. await base.DisposeAsync().ConfigureAwait(false);
  39. }
  40. protected override async ValueTask<bool> MoveNextCore()
  41. {
  42. switch (_state)
  43. {
  44. case AsyncIteratorState.Allocated:
  45. _enumerator = _source.GetAsyncEnumerator(_cancellationToken);
  46. _state = AsyncIteratorState.Iterating;
  47. goto case AsyncIteratorState.Iterating;
  48. case AsyncIteratorState.Iterating:
  49. while (await _enumerator.MoveNextAsync().ConfigureAwait(false))
  50. {
  51. }
  52. break; // case
  53. }
  54. await DisposeAsync().ConfigureAwait(false);
  55. return false;
  56. }
  57. }
  58. }
  59. }