IgnoreElements.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. #if USE_ASYNC_ITERATOR
  17. return AsyncEnumerable.Create(Core);
  18. async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
  19. {
  20. await foreach (var _ in AsyncEnumerableExtensions.WithCancellation(source, cancellationToken).ConfigureAwait(false))
  21. {
  22. }
  23. yield break;
  24. }
  25. #else
  26. return new IgnoreElementsAsyncIterator<TSource>(source);
  27. #endif
  28. }
  29. #if !USE_ASYNC_ITERATOR
  30. private sealed class IgnoreElementsAsyncIterator<TSource> : AsyncIterator<TSource>
  31. {
  32. private readonly IAsyncEnumerable<TSource> _source;
  33. private IAsyncEnumerator<TSource> _enumerator;
  34. public IgnoreElementsAsyncIterator(IAsyncEnumerable<TSource> source)
  35. {
  36. Debug.Assert(source != null);
  37. _source = source;
  38. }
  39. public override AsyncIteratorBase<TSource> Clone()
  40. {
  41. return new IgnoreElementsAsyncIterator<TSource>(_source);
  42. }
  43. public override async ValueTask DisposeAsync()
  44. {
  45. if (_enumerator != null)
  46. {
  47. await _enumerator.DisposeAsync().ConfigureAwait(false);
  48. _enumerator = null;
  49. }
  50. await base.DisposeAsync().ConfigureAwait(false);
  51. }
  52. protected override async ValueTask<bool> MoveNextCore()
  53. {
  54. switch (_state)
  55. {
  56. case AsyncIteratorState.Allocated:
  57. _enumerator = _source.GetAsyncEnumerator(_cancellationToken);
  58. _state = AsyncIteratorState.Iterating;
  59. goto case AsyncIteratorState.Iterating;
  60. case AsyncIteratorState.Iterating:
  61. while (await _enumerator.MoveNextAsync().ConfigureAwait(false))
  62. {
  63. }
  64. break; // case
  65. }
  66. await DisposeAsync().ConfigureAwait(false);
  67. return false;
  68. }
  69. }
  70. #endif
  71. }
  72. }