AsyncEnumerator.cs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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.Diagnostics;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace System.Collections.Generic
  9. {
  10. /// <summary>
  11. /// Provides a set of extension methods for <see cref="IAsyncEnumerator{T}"/>.
  12. /// </summary>
  13. public static class AsyncEnumerator
  14. {
  15. /// <summary>
  16. /// Creates a new enumerator using the specified delegates implementing the members of <see cref="IAsyncEnumerator{T}"/>.
  17. /// </summary>
  18. /// <typeparam name="T">The type of the elements returned by the enumerator.</typeparam>
  19. /// <param name="moveNext">The delegate implementing the <see cref="IAsyncEnumerator{T}.MoveNextAsync"/> method.</param>
  20. /// <param name="current">The delegate implementing the <see cref="IAsyncEnumerator{T}.Current"/> property getter.</param>
  21. /// <param name="dispose">The delegate implementing the <see cref="IAsyncDisposable.DisposeAsync"/> method.</param>
  22. /// <returns>A new enumerator instance.</returns>
  23. public static IAsyncEnumerator<T> Create<T>(Func<ValueTask<bool>> moveNext, Func<T> current, Func<ValueTask> dispose)
  24. {
  25. if (moveNext == null)
  26. throw Error.ArgumentNull(nameof(moveNext));
  27. // Note: Many methods pass null in for the second two params. We're assuming
  28. // That the caller is responsible and knows what they're doing
  29. return new AnonymousAsyncIterator<T>(moveNext, current, dispose);
  30. }
  31. /// <summary>
  32. /// Advances the enumerator to the next element in the sequence, returning the result asynchronously.
  33. /// </summary>
  34. /// <typeparam name="T">The type of the elements returned by the enumerator.</typeparam>
  35. /// <param name="source">The enumerator to advance.</param>
  36. /// <param name="cancellationToken">Cancellation token that can be used to cancel the operation.</param>
  37. /// <returns>
  38. /// Task containing the result of the operation: true if the enumerator was successfully advanced
  39. /// to the next element; false if the enumerator has passed the end of the sequence.
  40. /// </returns>
  41. public static ValueTask<bool> MoveNextAsync<T>(this IAsyncEnumerator<T> source, CancellationToken cancellationToken)
  42. {
  43. if (source == null)
  44. throw Error.ArgumentNull(nameof(source));
  45. cancellationToken.ThrowIfCancellationRequested();
  46. return source.MoveNextAsync();
  47. }
  48. /// <summary>
  49. /// Wraps the specified enumerator with an enumerator that checks for cancellation upon every invocation
  50. /// of the <see cref="IAsyncEnumerator{T}.MoveNextAsync"/> method.
  51. /// </summary>
  52. /// <typeparam name="T">The type of the elements returned by the enumerator.</typeparam>
  53. /// <param name="source">The enumerator to augment with cancellation support.</param>
  54. /// <param name="cancellationToken">The cancellation token to observe.</param>
  55. /// <returns>An enumerator that honors cancellation requests.</returns>
  56. public static IAsyncEnumerator<T> WithCancellation<T>(this IAsyncEnumerator<T> source, CancellationToken cancellationToken)
  57. {
  58. if (source == null)
  59. throw Error.ArgumentNull(nameof(source));
  60. return new AnonymousAsyncIterator<T>(
  61. moveNext: () =>
  62. {
  63. cancellationToken.ThrowIfCancellationRequested();
  64. return source.MoveNextAsync();
  65. },
  66. currentFunc: () => source.Current,
  67. dispose: source.DisposeAsync
  68. );
  69. }
  70. internal static IAsyncEnumerator<T> Create<T>(Func<TaskCompletionSource<bool>, ValueTask<bool>> moveNext, Func<T> current, Func<ValueTask> dispose)
  71. {
  72. return new AnonymousAsyncIterator<T>(
  73. async () =>
  74. {
  75. var tcs = new TaskCompletionSource<bool>();
  76. return await moveNext(tcs).ConfigureAwait(false);
  77. },
  78. current,
  79. dispose
  80. );
  81. }
  82. private sealed class AnonymousAsyncIterator<T> : AsyncIterator<T>
  83. {
  84. private readonly Func<T> _currentFunc;
  85. private readonly Func<ValueTask<bool>> _moveNext;
  86. private Func<ValueTask> _dispose;
  87. public AnonymousAsyncIterator(Func<ValueTask<bool>> moveNext, Func<T> currentFunc, Func<ValueTask> dispose)
  88. {
  89. Debug.Assert(moveNext != null);
  90. _moveNext = moveNext;
  91. _currentFunc = currentFunc;
  92. _dispose = dispose;
  93. // Explicit call to initialize enumerator mode
  94. GetAsyncEnumerator(default);
  95. }
  96. public override AsyncIteratorBase<T> Clone()
  97. {
  98. throw new NotSupportedException("AnonymousAsyncIterator cannot be cloned. It is only intended for use as an iterator.");
  99. }
  100. public override async ValueTask DisposeAsync()
  101. {
  102. var dispose = Interlocked.Exchange(ref _dispose, null);
  103. if (dispose != null)
  104. {
  105. await dispose().ConfigureAwait(false);
  106. }
  107. await base.DisposeAsync().ConfigureAwait(false);
  108. }
  109. protected override async ValueTask<bool> MoveNextCore()
  110. {
  111. switch (_state)
  112. {
  113. case AsyncIteratorState.Allocated:
  114. _state = AsyncIteratorState.Iterating;
  115. goto case AsyncIteratorState.Iterating;
  116. case AsyncIteratorState.Iterating:
  117. if (await _moveNext().ConfigureAwait(false))
  118. {
  119. _current = _currentFunc();
  120. return true;
  121. }
  122. await DisposeAsync().ConfigureAwait(false);
  123. break;
  124. }
  125. return false;
  126. }
  127. }
  128. }
  129. }