AsyncEnumerator.WithCancellation.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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.Threading;
  5. using System.Threading.Tasks;
  6. namespace System.Collections.Generic
  7. {
  8. public static partial class AsyncEnumerator
  9. {
  10. /// <summary>
  11. /// Wraps the specified enumerator with an enumerator that checks for cancellation upon every invocation
  12. /// of the <see cref="IAsyncEnumerator{T}.MoveNextAsync"/> method.
  13. /// </summary>
  14. /// <typeparam name="T">The type of the elements returned by the enumerator.</typeparam>
  15. /// <param name="source">The enumerator to augment with cancellation support.</param>
  16. /// <param name="cancellationToken">The cancellation token to observe.</param>
  17. /// <returns>An enumerator that honors cancellation requests.</returns>
  18. public static IAsyncEnumerator<T> WithCancellation<T>(this IAsyncEnumerator<T> source, CancellationToken cancellationToken)
  19. {
  20. if (source == null)
  21. throw Error.ArgumentNull(nameof(source));
  22. if (cancellationToken == default)
  23. return source;
  24. return new WithCancellationAsyncEnumerator<T>(source, cancellationToken);
  25. }
  26. private sealed class WithCancellationAsyncEnumerator<T> : IAsyncEnumerator<T>
  27. {
  28. private readonly IAsyncEnumerator<T> _source;
  29. private readonly CancellationToken _cancellationToken;
  30. public WithCancellationAsyncEnumerator(IAsyncEnumerator<T> source, CancellationToken cancellationToken)
  31. {
  32. _source = source;
  33. _cancellationToken = cancellationToken;
  34. }
  35. public T Current => _source.Current;
  36. public ValueTask DisposeAsync() => _source.DisposeAsync();
  37. public ValueTask<bool> MoveNextAsync()
  38. {
  39. _cancellationToken.ThrowIfCancellationRequested();
  40. return _source.MoveNextAsync(); // REVIEW: Signal cancellation through task or synchronously?
  41. }
  42. }
  43. }
  44. }