AsyncEnumerator.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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<Task<bool>> moveNext, Func<T> current, Func<Task> dispose)
  24. {
  25. if (moveNext == null)
  26. throw new ArgumentNullException(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 Task<bool> MoveNextAsync<T>(this IAsyncEnumerator<T> source, CancellationToken cancellationToken)
  42. {
  43. if (source == null)
  44. throw new ArgumentNullException(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 new ArgumentNullException(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. /// <summary>
  71. /// Wraps the specified enumerator in an enumerable.
  72. /// </summary>
  73. /// <typeparam name="T">The type of the elements returned by the enumerator.</typeparam>
  74. /// <param name="source">The enumerator to wrap.</param>
  75. /// <returns>An enumerable wrapping the specified enumerator.</returns>
  76. public static IAsyncEnumerable<T> AsEnumerable<T>(this IAsyncEnumerator<T> source)
  77. {
  78. if (source == null)
  79. throw new ArgumentNullException(nameof(source));
  80. return AsyncEnumerable.CreateEnumerable<T>(() => source);
  81. }
  82. internal static IAsyncEnumerator<T> Create<T>(Func<TaskCompletionSource<bool>, Task<bool>> moveNext, Func<T> current, Func<Task> dispose)
  83. {
  84. return new AnonymousAsyncIterator<T>(
  85. async () =>
  86. {
  87. var tcs = new TaskCompletionSource<bool>();
  88. return await moveNext(tcs).ConfigureAwait(false);
  89. },
  90. current,
  91. dispose
  92. );
  93. }
  94. private sealed class AnonymousAsyncIterator<T> : AsyncIterator<T>
  95. {
  96. private readonly Func<T> currentFunc;
  97. private readonly Func<Task<bool>> moveNext;
  98. private Func<Task> dispose;
  99. public AnonymousAsyncIterator(Func<Task<bool>> moveNext, Func<T> currentFunc, Func<Task> dispose)
  100. {
  101. Debug.Assert(moveNext != null);
  102. this.moveNext = moveNext;
  103. this.currentFunc = currentFunc;
  104. this.dispose = dispose;
  105. // Explicit call to initialize enumerator mode
  106. GetAsyncEnumerator();
  107. }
  108. public override AsyncIterator<T> Clone()
  109. {
  110. throw new NotSupportedException("AnonymousAsyncIterator cannot be cloned. It is only intended for use as an iterator.");
  111. }
  112. public override async Task DisposeAsync()
  113. {
  114. var dispose = Interlocked.Exchange(ref this.dispose, null);
  115. if (dispose != null)
  116. {
  117. await dispose().ConfigureAwait(false);
  118. }
  119. await base.DisposeAsync().ConfigureAwait(false);
  120. }
  121. protected override async Task<bool> MoveNextCore()
  122. {
  123. switch (state)
  124. {
  125. case AsyncIteratorState.Allocated:
  126. state = AsyncIteratorState.Iterating;
  127. goto case AsyncIteratorState.Iterating;
  128. case AsyncIteratorState.Iterating:
  129. if (await moveNext().ConfigureAwait(false))
  130. {
  131. current = currentFunc();
  132. return true;
  133. }
  134. await DisposeAsync().ConfigureAwait(false);
  135. break;
  136. }
  137. return false;
  138. }
  139. }
  140. }
  141. }