Generate.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. using System.Threading;
  6. namespace System.Linq
  7. {
  8. public static partial class AsyncEnumerableEx
  9. {
  10. // REVIEW: Add async variant?
  11. /// <summary>
  12. /// Generates an async-enumerable sequence by running a state-driven loop producing the sequence's elements.
  13. /// </summary>
  14. /// <typeparam name="TState">The type of the state used in the generator loop.</typeparam>
  15. /// <typeparam name="TResult">The type of the elements in the produced sequence.</typeparam>
  16. /// <param name="initialState">Initial state.</param>
  17. /// <param name="condition">Condition to terminate generation (upon returning false).</param>
  18. /// <param name="iterate">Iteration step function.</param>
  19. /// <param name="resultSelector">Selector function for results produced in the sequence.</param>
  20. /// <returns>The generated sequence.</returns>
  21. /// <exception cref="ArgumentNullException"><paramref name="condition"/> or <paramref name="iterate"/> or <paramref name="resultSelector"/> is null.</exception>
  22. public static IAsyncEnumerable<TResult> Generate<TState, TResult>(TState initialState, Func<TState, bool> condition, Func<TState, TState> iterate, Func<TState, TResult> resultSelector)
  23. {
  24. if (condition == null)
  25. throw Error.ArgumentNull(nameof(condition));
  26. if (iterate == null)
  27. throw Error.ArgumentNull(nameof(iterate));
  28. if (resultSelector == null)
  29. throw Error.ArgumentNull(nameof(resultSelector));
  30. #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
  31. return Core(initialState, condition, iterate, resultSelector);
  32. static async IAsyncEnumerable<TResult> Core(TState initialState, Func<TState, bool> condition, Func<TState, TState> iterate, Func<TState, TResult> resultSelector, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
  33. {
  34. for (var state = initialState; condition(state); state = iterate(state))
  35. {
  36. // REVIEW: Check for cancellation?
  37. yield return resultSelector(state);
  38. }
  39. }
  40. #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
  41. }
  42. }
  43. }