AsyncEnumerator.cs 4.9 KB

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