EveryUpdate.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System.Threading;
  2. namespace Cysharp.Threading.Tasks.Linq
  3. {
  4. public static partial class UniTaskAsyncEnumerable
  5. {
  6. public static IUniTaskAsyncEnumerable<AsyncUnit> EveryUpdate(PlayerLoopTiming updateTiming = PlayerLoopTiming.Update)
  7. {
  8. return new EveryUpdate(updateTiming);
  9. }
  10. }
  11. internal class EveryUpdate : IUniTaskAsyncEnumerable<AsyncUnit>
  12. {
  13. readonly PlayerLoopTiming updateTiming;
  14. public EveryUpdate(PlayerLoopTiming updateTiming)
  15. {
  16. this.updateTiming = updateTiming;
  17. }
  18. public IUniTaskAsyncEnumerator<AsyncUnit> GetAsyncEnumerator(CancellationToken cancellationToken = default)
  19. {
  20. return new _EveryUpdate(updateTiming, cancellationToken);
  21. }
  22. class _EveryUpdate : MoveNextSource, IUniTaskAsyncEnumerator<AsyncUnit>, IPlayerLoopItem
  23. {
  24. readonly PlayerLoopTiming updateTiming;
  25. CancellationToken cancellationToken;
  26. bool disposed;
  27. public _EveryUpdate(PlayerLoopTiming updateTiming, CancellationToken cancellationToken)
  28. {
  29. this.updateTiming = updateTiming;
  30. this.cancellationToken = cancellationToken;
  31. TaskTracker.TrackActiveTask(this, 2);
  32. PlayerLoopHelper.AddAction(updateTiming, this);
  33. }
  34. public AsyncUnit Current => default;
  35. public UniTask<bool> MoveNextAsync()
  36. {
  37. // return false instead of throw
  38. if (disposed || cancellationToken.IsCancellationRequested) return CompletedTasks.False;
  39. completionSource.Reset();
  40. return new UniTask<bool>(this, completionSource.Version);
  41. }
  42. public UniTask DisposeAsync()
  43. {
  44. if (!disposed)
  45. {
  46. disposed = true;
  47. TaskTracker.RemoveTracking(this);
  48. }
  49. return default;
  50. }
  51. public bool MoveNext()
  52. {
  53. if (disposed || cancellationToken.IsCancellationRequested)
  54. {
  55. completionSource.TrySetResult(false);
  56. return false;
  57. }
  58. completionSource.TrySetResult(true);
  59. return true;
  60. }
  61. }
  62. }
  63. }