AsyncEnumerable.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT 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. #if INCLUDE_RELOCATED_TO_INTERACTIVE_ASYNC
  9. /// <summary>
  10. /// Provides a set of extension methods for <see cref="IAsyncEnumerable{T}"/>.
  11. /// </summary>
  12. public static partial class AsyncEnumerable
  13. {
  14. //
  15. // NOTE: This has been replaced in v7 by a method of the same name on
  16. // System.Interactive.Async's AsyncEnumerableEx class. This is a breaking
  17. // change but it's necessary because we can't allow System.Linq.Async's
  18. // ref assembly to define a public AsyncEnumerable type. If we do that,
  19. // it will conflict with System.Linq.AsyncEnumerable, preventing direct
  20. // invocation of static methods. (E.g., AsyncEnumerable.Range.)
  21. //
  22. /// <summary>
  23. /// Creates a new enumerable using the specified delegates implementing the members of <see cref="IAsyncEnumerable{T}"/>.
  24. /// </summary>
  25. /// <typeparam name="T">The type of the elements returned by the enumerable sequence.</typeparam>
  26. /// <param name="getAsyncEnumerator">The delegate implementing the <see cref="IAsyncEnumerable{T}.GetAsyncEnumerator"/> method.</param>
  27. /// <returns>A new enumerable instance.</returns>
  28. public static IAsyncEnumerable<T> Create<T>(Func<CancellationToken, IAsyncEnumerator<T>> getAsyncEnumerator)
  29. {
  30. if (getAsyncEnumerator == null)
  31. throw Error.ArgumentNull(nameof(getAsyncEnumerator));
  32. return new AnonymousAsyncEnumerable<T>(getAsyncEnumerator);
  33. }
  34. private sealed class AnonymousAsyncEnumerable<T> : IAsyncEnumerable<T>
  35. {
  36. private readonly Func<CancellationToken, IAsyncEnumerator<T>> _getEnumerator;
  37. public AnonymousAsyncEnumerable(Func<CancellationToken, IAsyncEnumerator<T>> getEnumerator) => _getEnumerator = getEnumerator;
  38. public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken)
  39. {
  40. cancellationToken.ThrowIfCancellationRequested(); // NB: [LDM-2018-11-28] Equivalent to async iterator behavior.
  41. return _getEnumerator(cancellationToken);
  42. }
  43. }
  44. }
  45. #endif // INCLUDE_RELOCATED_TO_INTERACTIVE_ASYNC
  46. }