IgnoreElements.cs 2.7 KB

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