ToAsyncEnumerable.Task.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 AsyncEnumerable
  9. {
  10. #if INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  11. // Moved to AsyncEnumerableEx in System.Interactive.Async.
  12. // System.Linq.AsyncEnumerable has chosen not to implement this. We continue to implement this because
  13. // we believe it is a useful feature, but since it's now in the category of LINQ-adjacent functionality
  14. // not built into the .NET runtime libraries, it now lives in System.Interactive.Async.
  15. /// <summary>
  16. /// Converts a task to an async-enumerable sequence.
  17. /// </summary>
  18. /// <typeparam name="TSource">The type of the elements in the source task.</typeparam>
  19. /// <param name="task">Task to convert to an async-enumerable sequence.</param>
  20. /// <returns>The async-enumerable sequence whose element is pulled from the given task.</returns>
  21. /// <exception cref="ArgumentNullException"><paramref name="task"/> is null.</exception>
  22. public static IAsyncEnumerable<TSource> ToAsyncEnumerable<TSource>(this Task<TSource> task)
  23. {
  24. if (task == null)
  25. throw Error.ArgumentNull(nameof(task));
  26. return new TaskToAsyncEnumerable<TSource>(task);
  27. }
  28. private sealed class TaskToAsyncEnumerable<T> : AsyncIterator<T>
  29. {
  30. private readonly Task<T> _task;
  31. public TaskToAsyncEnumerable(Task<T> task) => _task = task;
  32. public override AsyncIteratorBase<T> Clone() => new TaskToAsyncEnumerable<T>(_task);
  33. protected override async ValueTask<bool> MoveNextCore()
  34. {
  35. if (_state == AsyncIteratorState.Allocated)
  36. {
  37. _state = AsyncIteratorState.Iterating;
  38. _current = await _task.ConfigureAwait(false);
  39. return true;
  40. }
  41. return false;
  42. }
  43. }
  44. #endif // INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  45. }
  46. }