AsyncEnumerator.cs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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 partial class AsyncEnumerator
  14. {
  15. //
  16. // REVIEW: Create methods may not belong in System.Linq.Async. Async iterators can be
  17. // used to implement these interfaces. Move to System.Interactive.Async?
  18. //
  19. /// <summary>
  20. /// Creates a new enumerator using the specified delegates implementing the members of <see cref="IAsyncEnumerator{T}"/>.
  21. /// </summary>
  22. /// <typeparam name="T">The type of the elements returned by the enumerator.</typeparam>
  23. /// <param name="moveNextAsync">The delegate implementing the <see cref="IAsyncEnumerator{T}.MoveNextAsync"/> method.</param>
  24. /// <param name="getCurrent">The delegate implementing the <see cref="IAsyncEnumerator{T}.Current"/> property getter.</param>
  25. /// <param name="disposeAsync">The delegate implementing the <see cref="IAsyncDisposable.DisposeAsync"/> method.</param>
  26. /// <returns>A new enumerator instance.</returns>
  27. public static IAsyncEnumerator<T> Create<T>(Func<ValueTask<bool>> moveNextAsync, Func<T> getCurrent, Func<ValueTask> disposeAsync)
  28. {
  29. if (moveNextAsync == null)
  30. throw Error.ArgumentNull(nameof(moveNextAsync));
  31. //
  32. // NB: Callers can pass null for the second two parameters, which can be useful to
  33. // implement enumerators that throw or yield no results.
  34. //
  35. return new AnonymousAsyncIterator<T>(moveNextAsync, getCurrent, disposeAsync);
  36. }
  37. /// <summary>
  38. /// Advances the enumerator to the next element in the sequence, returning the result asynchronously.
  39. /// </summary>
  40. /// <typeparam name="T">The type of the elements returned by the enumerator.</typeparam>
  41. /// <param name="source">The enumerator to advance.</param>
  42. /// <param name="cancellationToken">Cancellation token that can be used to cancel the operation.</param>
  43. /// <returns>
  44. /// Task containing the result of the operation: true if the enumerator was successfully advanced
  45. /// to the next element; false if the enumerator has passed the end of the sequence.
  46. /// </returns>
  47. public static ValueTask<bool> MoveNextAsync<T>(this IAsyncEnumerator<T> source, CancellationToken cancellationToken)
  48. {
  49. if (source == null)
  50. throw Error.ArgumentNull(nameof(source));
  51. cancellationToken.ThrowIfCancellationRequested();
  52. return source.MoveNextAsync();
  53. }
  54. private sealed class AnonymousAsyncIterator<T> : AsyncIterator<T>
  55. {
  56. private readonly Func<T> _currentFunc;
  57. private readonly Func<ValueTask<bool>> _moveNext;
  58. private Func<ValueTask> _dispose;
  59. public AnonymousAsyncIterator(Func<ValueTask<bool>> moveNext, Func<T> currentFunc, Func<ValueTask> dispose)
  60. {
  61. Debug.Assert(moveNext != null);
  62. _moveNext = moveNext;
  63. _currentFunc = currentFunc;
  64. _dispose = dispose;
  65. // Explicit call to initialize enumerator mode
  66. GetAsyncEnumerator(default);
  67. }
  68. public override AsyncIteratorBase<T> Clone()
  69. {
  70. throw new NotSupportedException("AnonymousAsyncIterator cannot be cloned. It is only intended for use as an iterator.");
  71. }
  72. public override async ValueTask DisposeAsync()
  73. {
  74. var dispose = Interlocked.Exchange(ref _dispose, null);
  75. if (dispose != null)
  76. {
  77. await dispose().ConfigureAwait(false);
  78. }
  79. await base.DisposeAsync().ConfigureAwait(false);
  80. }
  81. protected override async ValueTask<bool> MoveNextCore()
  82. {
  83. switch (_state)
  84. {
  85. case AsyncIteratorState.Allocated:
  86. _state = AsyncIteratorState.Iterating;
  87. goto case AsyncIteratorState.Iterating;
  88. case AsyncIteratorState.Iterating:
  89. if (await _moveNext().ConfigureAwait(false))
  90. {
  91. _current = _currentFunc();
  92. return true;
  93. }
  94. await DisposeAsync().ConfigureAwait(false);
  95. break;
  96. }
  97. return false;
  98. }
  99. }
  100. }
  101. }