AsyncEnumerableExtensions.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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.Runtime.CompilerServices;
  6. namespace System.Threading.Tasks
  7. {
  8. public static class AsyncEnumerableExtensions
  9. {
  10. #if !BCL_HAS_CONFIGUREAWAIT // https://github.com/dotnet/coreclr/pull/21939
  11. /// <summary>Configures how awaits on the tasks returned from an async iteration will be performed.</summary>
  12. /// <typeparam name="T">The type of the objects being iterated.</typeparam>
  13. /// <param name="source">The source enumerable being iterated.</param>
  14. /// <param name="continueOnCapturedContext">Whether to capture and marshal back to the current context.</param>
  15. /// <returns>The configured enumerable.</returns>
  16. public static ConfiguredCancelableAsyncEnumerable<T> ConfigureAwait<T>(
  17. this IAsyncEnumerable<T> source, bool continueOnCapturedContext) =>
  18. new ConfiguredCancelableAsyncEnumerable<T>(source, continueOnCapturedContext, cancellationToken: default);
  19. /// <summary>Sets the <see cref="CancellationToken"/> to be passed to <see cref="IAsyncEnumerable{T}.GetAsyncEnumerator(CancellationToken)"/> when iterating.</summary>
  20. /// <typeparam name="T">The type of the objects being iterated.</typeparam>
  21. /// <param name="source">The source enumerable being iterated.</param>
  22. /// <param name="cancellationToken">The <see cref="CancellationToken"/> to use.</param>
  23. /// <returns>The configured enumerable.</returns>
  24. public static ConfiguredCancelableAsyncEnumerable<T> WithCancellation<T>(
  25. this IAsyncEnumerable<T> source, CancellationToken cancellationToken) =>
  26. new ConfiguredCancelableAsyncEnumerable<T>(source, continueOnCapturedContext: true, cancellationToken);
  27. #endif
  28. public static ConfiguredCancelableAsyncEnumerable<T>.Enumerator ConfigureAwait<T>(this IAsyncEnumerator<T> enumerator, bool continueOnCapturedContext)
  29. {
  30. if (enumerator == null)
  31. throw Error.ArgumentNull(nameof(enumerator));
  32. return new ConfiguredCancelableAsyncEnumerable<T>.Enumerator(enumerator, continueOnCapturedContext);
  33. }
  34. }
  35. }