AsyncEnumerable.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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.Threading;
  6. namespace System.Linq
  7. {
  8. /// <summary>
  9. /// Provides a set of extension methods for <see cref="IAsyncEnumerable{T}"/>.
  10. /// </summary>
  11. public static partial class AsyncEnumerable
  12. {
  13. //
  14. // REVIEW: Create methods may not belong in System.Linq.Async. Async iterators can be
  15. // used to implement these interfaces. Move to System.Interactive.Async?
  16. //
  17. /// <summary>
  18. /// Creates a new enumerable using the specified delegates implementing the members of <see cref="IAsyncEnumerable{T}"/>.
  19. /// </summary>
  20. /// <typeparam name="T">The type of the elements returned by the enumerable sequence.</typeparam>
  21. /// <param name="getAsyncEnumerator">The delegate implementing the <see cref="IAsyncEnumerable{T}.GetAsyncEnumerator"/> method.</param>
  22. /// <returns>A new enumerable instance.</returns>
  23. public static IAsyncEnumerable<T> Create<T>(Func<CancellationToken, IAsyncEnumerator<T>> getAsyncEnumerator)
  24. {
  25. if (getAsyncEnumerator == null)
  26. throw Error.ArgumentNull(nameof(getAsyncEnumerator));
  27. return new AnonymousAsyncEnumerable<T>(getAsyncEnumerator);
  28. }
  29. private sealed class AnonymousAsyncEnumerable<T> : IAsyncEnumerable<T>
  30. {
  31. private readonly Func<CancellationToken, IAsyncEnumerator<T>> _getEnumerator;
  32. public AnonymousAsyncEnumerable(Func<CancellationToken, IAsyncEnumerator<T>> getEnumerator) => _getEnumerator = getEnumerator;
  33. public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken)
  34. {
  35. cancellationToken.ThrowIfCancellationRequested(); // NB: [LDM-2018-11-28] Equivalent to async iterator behavior.
  36. return _getEnumerator(cancellationToken);
  37. }
  38. }
  39. }
  40. }