ToAsyncEnumerable.Task.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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.Tasks;
  6. namespace System.Linq
  7. {
  8. public static partial class AsyncEnumerableEx
  9. {
  10. /// <summary>
  11. /// Converts a task to an async-enumerable sequence.
  12. /// </summary>
  13. /// <typeparam name="TSource">The type of the elements in the source task.</typeparam>
  14. /// <param name="task">Task to convert to an async-enumerable sequence.</param>
  15. /// <returns>The async-enumerable sequence whose element is pulled from the given task.</returns>
  16. /// <exception cref="ArgumentNullException"><paramref name="task"/> is null.</exception>
  17. public static IAsyncEnumerable<TSource> ToAsyncEnumerable<TSource>(this Task<TSource> task)
  18. {
  19. if (task == null)
  20. throw Error.ArgumentNull(nameof(task));
  21. return new TaskToAsyncEnumerable<TSource>(task);
  22. }
  23. private sealed class TaskToAsyncEnumerable<T> : AsyncIterator<T>
  24. {
  25. private readonly Task<T> _task;
  26. public TaskToAsyncEnumerable(Task<T> task) => _task = task;
  27. public override AsyncIteratorBase<T> Clone() => new TaskToAsyncEnumerable<T>(_task);
  28. protected override async ValueTask<bool> MoveNextCore()
  29. {
  30. if (_state == AsyncIteratorState.Allocated)
  31. {
  32. _state = AsyncIteratorState.Iterating;
  33. _current = await _task.ConfigureAwait(false);
  34. return true;
  35. }
  36. return false;
  37. }
  38. }
  39. }
  40. }