IgnoreElements.cs 2.3 KB

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