ToAsyncEnumerable.Task.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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.Collections.Generic;
  5. using System.Threading.Tasks;
  6. namespace System.Linq
  7. {
  8. public static partial class AsyncEnumerable
  9. {
  10. public static IAsyncEnumerable<TSource> ToAsyncEnumerable<TSource>(this Task<TSource> task)
  11. {
  12. if (task == null)
  13. throw Error.ArgumentNull(nameof(task));
  14. return new TaskToAsyncEnumerable<TSource>(task);
  15. }
  16. private sealed class TaskToAsyncEnumerable<T> : AsyncIterator<T>
  17. {
  18. private readonly Task<T> _task;
  19. public TaskToAsyncEnumerable(Task<T> task) => _task = task;
  20. public override AsyncIteratorBase<T> Clone() => new TaskToAsyncEnumerable<T>(_task);
  21. protected override async ValueTask<bool> MoveNextCore()
  22. {
  23. if (_state == AsyncIteratorState.Allocated)
  24. {
  25. _state = AsyncIteratorState.Iterating;
  26. _current = await _task.ConfigureAwait(false);
  27. return true;
  28. }
  29. return false;
  30. }
  31. }
  32. }
  33. }