TaskYieldInstruction.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using System;
  2. using UnityEngine;
  3. using System.Threading.Tasks;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. namespace UnityAsync
  7. {
  8. /// <summary>
  9. /// Encapsulates a <see cref="System.Threading.Tasks.Task"/>, allowing it to be yielded in an IEnumerator coroutine.
  10. /// </summary>
  11. public class TaskYieldInstruction : CustomYieldInstruction
  12. {
  13. readonly Task task;
  14. public TaskYieldInstruction(Task task) => this.task = task;
  15. public override bool keepWaiting => !task.IsCompleted;
  16. }
  17. /// <summary>
  18. /// Encapsulates a <see cref="System.Threading.Tasks.Task{TResult}"/>, allowing it to be yielded in an IEnumerator coroutine.
  19. /// </summary>
  20. public class TaskYieldInstruction<TResult> : IEnumerator<TResult>
  21. {
  22. readonly Task<TResult> task;
  23. public TaskYieldInstruction(Task<TResult> task) => this.task = task;
  24. object IEnumerator.Current => Current;
  25. /// <summary>
  26. /// Returns the encapsulated <see cref="System.Threading.Tasks.Task{TResult}"/>'s result if it has completed, otherwise the
  27. /// default TResult value.
  28. /// </summary>
  29. public TResult Current => task.IsCompleted ? task.Result : default;
  30. public void Dispose() => task.Dispose();
  31. public bool MoveNext() => !task.IsCompleted;
  32. public void Reset() => throw new NotSupportedException();
  33. }
  34. }