IgnoreElements.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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.Tasks;
  7. namespace System.Linq
  8. {
  9. public static partial class AsyncEnumerableEx
  10. {
  11. public static IAsyncEnumerable<TSource> IgnoreElements<TSource>(this IAsyncEnumerable<TSource> source)
  12. {
  13. if (source == null)
  14. throw new ArgumentNullException(nameof(source));
  15. return new IgnoreElementsAsyncIterator<TSource>(source);
  16. }
  17. private sealed class IgnoreElementsAsyncIterator<TSource> : AsyncIterator<TSource>
  18. {
  19. private readonly IAsyncEnumerable<TSource> source;
  20. private IAsyncEnumerator<TSource> enumerator;
  21. public IgnoreElementsAsyncIterator(IAsyncEnumerable<TSource> source)
  22. {
  23. Debug.Assert(source != null);
  24. this.source = source;
  25. }
  26. public override AsyncIterator<TSource> Clone()
  27. {
  28. return new IgnoreElementsAsyncIterator<TSource>(source);
  29. }
  30. public override async Task DisposeAsync()
  31. {
  32. if (enumerator != null)
  33. {
  34. await enumerator.DisposeAsync().ConfigureAwait(false);
  35. enumerator = null;
  36. }
  37. await base.DisposeAsync().ConfigureAwait(false);
  38. }
  39. protected override async Task<bool> MoveNextCore()
  40. {
  41. switch (state)
  42. {
  43. case AsyncIteratorState.Allocated:
  44. enumerator = source.GetAsyncEnumerator();
  45. state = AsyncIteratorState.Iterating;
  46. goto case AsyncIteratorState.Iterating;
  47. case AsyncIteratorState.Iterating:
  48. while (await enumerator.MoveNextAsync().ConfigureAwait(false))
  49. {
  50. }
  51. break; // case
  52. }
  53. await DisposeAsync().ConfigureAwait(false);
  54. return false;
  55. }
  56. }
  57. }
  58. }