ToAsyncEnumerable.Task.cs 1.3 KB

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