IgnoreElements.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 Create(() =>
  18. {
  19. var e = source.GetEnumerator();
  20. var cts = new CancellationTokenDisposable();
  21. var d = Disposable.Create(cts, e);
  22. var f = default(Func<CancellationToken, Task<bool>>);
  23. f = async ct =>
  24. {
  25. if (!await e.MoveNext(ct)
  26. .ConfigureAwait(false))
  27. {
  28. return false;
  29. }
  30. return await f(ct)
  31. .ConfigureAwait(false);
  32. };
  33. return Create<TSource>(
  34. f,
  35. () => { throw new InvalidOperationException(); },
  36. d.Dispose,
  37. e
  38. );
  39. });
  40. }
  41. }
  42. }