AsyncEnumerator.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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. internal static IAsyncEnumerator<T> Create<T>(Func<TaskCompletionSource<bool>, Task<bool>> moveNext, Func<T> current, Func<Task> dispose)
  49. {
  50. return new AnonymousAsyncIterator<T>(
  51. async () =>
  52. {
  53. var tcs = new TaskCompletionSource<bool>();
  54. return await moveNext(tcs).ConfigureAwait(false);
  55. },
  56. current,
  57. dispose
  58. );
  59. }
  60. private sealed class AnonymousAsyncIterator<T> : AsyncIterator<T>
  61. {
  62. private readonly Func<T> currentFunc;
  63. private readonly Func<Task> dispose;
  64. private readonly Func<Task<bool>> moveNext;
  65. public AnonymousAsyncIterator(Func<Task<bool>> moveNext, Func<T> currentFunc, Func<Task> dispose)
  66. {
  67. Debug.Assert(moveNext != null);
  68. this.moveNext = moveNext;
  69. this.currentFunc = currentFunc;
  70. this.dispose = dispose;
  71. // Explicit call to initialize enumerator mode
  72. GetAsyncEnumerator();
  73. }
  74. public override AsyncIterator<T> Clone()
  75. {
  76. throw new NotSupportedException("AnonymousAsyncIterator cannot be cloned. It is only intended for use as an iterator.");
  77. }
  78. public override async Task DisposeAsync()
  79. {
  80. if (dispose != null)
  81. {
  82. await dispose().ConfigureAwait(false);
  83. }
  84. await base.DisposeAsync().ConfigureAwait(false);
  85. }
  86. protected override async Task<bool> MoveNextCore()
  87. {
  88. switch (state)
  89. {
  90. case AsyncIteratorState.Allocated:
  91. state = AsyncIteratorState.Iterating;
  92. goto case AsyncIteratorState.Iterating;
  93. case AsyncIteratorState.Iterating:
  94. if (await moveNext().ConfigureAwait(false))
  95. {
  96. current = currentFunc();
  97. return true;
  98. }
  99. await DisposeAsync().ConfigureAwait(false);
  100. break;
  101. }
  102. return false;
  103. }
  104. }
  105. }
  106. }