IgnoreElements.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace System.Linq
  10. {
  11. public static partial class AsyncEnumerable
  12. {
  13. public static IAsyncEnumerable<TSource> IgnoreElements<TSource>(this IAsyncEnumerable<TSource> source)
  14. {
  15. if (source == null)
  16. throw new ArgumentNullException(nameof(source));
  17. return CreateEnumerable(
  18. () =>
  19. {
  20. var e = source.GetEnumerator();
  21. var cts = new CancellationTokenDisposable();
  22. var d = Disposable.Create(cts, e);
  23. var f = default(Func<CancellationToken, Task<bool>>);
  24. f = async ct =>
  25. {
  26. if (!await e.MoveNext(ct)
  27. .ConfigureAwait(false))
  28. {
  29. return false;
  30. }
  31. return await f(ct)
  32. .ConfigureAwait(false);
  33. };
  34. return CreateEnumerator<TSource>(
  35. f,
  36. () => { throw new InvalidOperationException(); },
  37. d.Dispose,
  38. e
  39. );
  40. });
  41. }
  42. }
  43. }