UniTask.Delay.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  1. #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
  2. using Cysharp.Threading.Tasks.Internal;
  3. using System;
  4. using System.Collections;
  5. using System.Runtime.CompilerServices;
  6. using System.Threading;
  7. using UnityEngine;
  8. namespace Cysharp.Threading.Tasks
  9. {
  10. public enum DelayType
  11. {
  12. /// <summary>use Time.deltaTime.</summary>
  13. DeltaTime,
  14. /// <summary>Ignore timescale, use Time.unscaledDeltaTime.</summary>
  15. UnscaledDeltaTime,
  16. /// <summary>use Stopwatch.GetTimestamp().</summary>
  17. Realtime
  18. }
  19. public partial struct UniTask
  20. {
  21. public static YieldAwaitable Yield()
  22. {
  23. // optimized for single continuation
  24. return new YieldAwaitable(PlayerLoopTiming.Update);
  25. }
  26. public static YieldAwaitable Yield(PlayerLoopTiming timing)
  27. {
  28. // optimized for single continuation
  29. return new YieldAwaitable(timing);
  30. }
  31. public static UniTask Yield(CancellationToken cancellationToken)
  32. {
  33. return new UniTask(YieldPromise.Create(PlayerLoopTiming.Update, cancellationToken, out var token), token);
  34. }
  35. public static UniTask Yield(PlayerLoopTiming timing, CancellationToken cancellationToken)
  36. {
  37. return new UniTask(YieldPromise.Create(timing, cancellationToken, out var token), token);
  38. }
  39. /// <summary>
  40. /// Similar as UniTask.Yield but guaranteed run on next frame.
  41. /// </summary>
  42. public static UniTask NextFrame()
  43. {
  44. return new UniTask(NextFramePromise.Create(PlayerLoopTiming.Update, CancellationToken.None, out var token), token);
  45. }
  46. /// <summary>
  47. /// Similar as UniTask.Yield but guaranteed run on next frame.
  48. /// </summary>
  49. public static UniTask NextFrame(PlayerLoopTiming timing)
  50. {
  51. return new UniTask(NextFramePromise.Create(timing, CancellationToken.None, out var token), token);
  52. }
  53. /// <summary>
  54. /// Similar as UniTask.Yield but guaranteed run on next frame.
  55. /// </summary>
  56. public static UniTask NextFrame(CancellationToken cancellationToken)
  57. {
  58. return new UniTask(NextFramePromise.Create(PlayerLoopTiming.Update, cancellationToken, out var token), token);
  59. }
  60. /// <summary>
  61. /// Similar as UniTask.Yield but guaranteed run on next frame.
  62. /// </summary>
  63. public static UniTask NextFrame(PlayerLoopTiming timing, CancellationToken cancellationToken)
  64. {
  65. return new UniTask(NextFramePromise.Create(timing, cancellationToken, out var token), token);
  66. }
  67. [Obsolete("Use WaitForEndOfFrame(MonoBehaviour) instead or UniTask.Yield(PlayerLoopTiming.LastPostLateUpdate). Equivalent for coroutine's WaitForEndOfFrame requires MonoBehaviour(runner of Coroutine).")]
  68. public static YieldAwaitable WaitForEndOfFrame()
  69. {
  70. return UniTask.Yield(PlayerLoopTiming.LastPostLateUpdate);
  71. }
  72. [Obsolete("Use WaitForEndOfFrame(MonoBehaviour) instead or UniTask.Yield(PlayerLoopTiming.LastPostLateUpdate). Equivalent for coroutine's WaitForEndOfFrame requires MonoBehaviour(runner of Coroutine).")]
  73. public static UniTask WaitForEndOfFrame(CancellationToken cancellationToken)
  74. {
  75. return UniTask.Yield(PlayerLoopTiming.LastPostLateUpdate, cancellationToken);
  76. }
  77. public static UniTask WaitForEndOfFrame(MonoBehaviour coroutineRunner, CancellationToken cancellationToken = default)
  78. {
  79. var source = WaitForEndOfFramePromise.Create(coroutineRunner, cancellationToken, out var token);
  80. return new UniTask(source, token);
  81. }
  82. /// <summary>
  83. /// Same as UniTask.Yield(PlayerLoopTiming.LastFixedUpdate).
  84. /// </summary>
  85. public static YieldAwaitable WaitForFixedUpdate()
  86. {
  87. // use LastFixedUpdate instead of FixedUpdate
  88. // https://github.com/Cysharp/UniTask/issues/377
  89. return UniTask.Yield(PlayerLoopTiming.LastFixedUpdate);
  90. }
  91. /// <summary>
  92. /// Same as UniTask.Yield(PlayerLoopTiming.LastFixedUpdate, cancellationToken).
  93. /// </summary>
  94. public static UniTask WaitForFixedUpdate(CancellationToken cancellationToken)
  95. {
  96. return UniTask.Yield(PlayerLoopTiming.LastFixedUpdate, cancellationToken);
  97. }
  98. public static UniTask WaitForSeconds(float duration, bool ignoreTimeScale = false, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken))
  99. {
  100. return Delay(Mathf.RoundToInt(1000 * duration), ignoreTimeScale, delayTiming, cancellationToken);
  101. }
  102. public static UniTask WaitForSeconds(int duration, bool ignoreTimeScale = false, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken))
  103. {
  104. return Delay(1000 * duration, ignoreTimeScale, delayTiming, cancellationToken);
  105. }
  106. public static UniTask DelayFrame(int delayFrameCount, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken))
  107. {
  108. if (delayFrameCount < 0)
  109. {
  110. throw new ArgumentOutOfRangeException("Delay does not allow minus delayFrameCount. delayFrameCount:" + delayFrameCount);
  111. }
  112. return new UniTask(DelayFramePromise.Create(delayFrameCount, delayTiming, cancellationToken, out var token), token);
  113. }
  114. public static UniTask Delay(int millisecondsDelay, bool ignoreTimeScale = false, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken))
  115. {
  116. var delayTimeSpan = TimeSpan.FromMilliseconds(millisecondsDelay);
  117. return Delay(delayTimeSpan, ignoreTimeScale, delayTiming, cancellationToken);
  118. }
  119. public static UniTask Delay(TimeSpan delayTimeSpan, bool ignoreTimeScale = false, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken))
  120. {
  121. var delayType = ignoreTimeScale ? DelayType.UnscaledDeltaTime : DelayType.DeltaTime;
  122. return Delay(delayTimeSpan, delayType, delayTiming, cancellationToken);
  123. }
  124. public static UniTask Delay(int millisecondsDelay, DelayType delayType, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken))
  125. {
  126. var delayTimeSpan = TimeSpan.FromMilliseconds(millisecondsDelay);
  127. return Delay(delayTimeSpan, delayType, delayTiming, cancellationToken);
  128. }
  129. public static UniTask Delay(TimeSpan delayTimeSpan, DelayType delayType, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken))
  130. {
  131. if (delayTimeSpan < TimeSpan.Zero)
  132. {
  133. throw new ArgumentOutOfRangeException("Delay does not allow minus delayTimeSpan. delayTimeSpan:" + delayTimeSpan);
  134. }
  135. #if UNITY_EDITOR
  136. // force use Realtime.
  137. if (PlayerLoopHelper.IsMainThread && !UnityEditor.EditorApplication.isPlaying)
  138. {
  139. delayType = DelayType.Realtime;
  140. }
  141. #endif
  142. switch (delayType)
  143. {
  144. case DelayType.UnscaledDeltaTime:
  145. {
  146. return new UniTask(DelayIgnoreTimeScalePromise.Create(delayTimeSpan, delayTiming, cancellationToken, out var token), token);
  147. }
  148. case DelayType.Realtime:
  149. {
  150. return new UniTask(DelayRealtimePromise.Create(delayTimeSpan, delayTiming, cancellationToken, out var token), token);
  151. }
  152. case DelayType.DeltaTime:
  153. default:
  154. {
  155. return new UniTask(DelayPromise.Create(delayTimeSpan, delayTiming, cancellationToken, out var token), token);
  156. }
  157. }
  158. }
  159. sealed class YieldPromise : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode<YieldPromise>
  160. {
  161. static TaskPool<YieldPromise> pool;
  162. YieldPromise nextNode;
  163. public ref YieldPromise NextNode => ref nextNode;
  164. static YieldPromise()
  165. {
  166. TaskPool.RegisterSizeGetter(typeof(YieldPromise), () => pool.Size);
  167. }
  168. CancellationToken cancellationToken;
  169. UniTaskCompletionSourceCore<object> core;
  170. YieldPromise()
  171. {
  172. }
  173. public static IUniTaskSource Create(PlayerLoopTiming timing, CancellationToken cancellationToken, out short token)
  174. {
  175. if (cancellationToken.IsCancellationRequested)
  176. {
  177. return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token);
  178. }
  179. if (!pool.TryPop(out var result))
  180. {
  181. result = new YieldPromise();
  182. }
  183. result.cancellationToken = cancellationToken;
  184. TaskTracker.TrackActiveTask(result, 3);
  185. PlayerLoopHelper.AddAction(timing, result);
  186. token = result.core.Version;
  187. return result;
  188. }
  189. public void GetResult(short token)
  190. {
  191. try
  192. {
  193. core.GetResult(token);
  194. }
  195. finally
  196. {
  197. TryReturn();
  198. }
  199. }
  200. public UniTaskStatus GetStatus(short token)
  201. {
  202. return core.GetStatus(token);
  203. }
  204. public UniTaskStatus UnsafeGetStatus()
  205. {
  206. return core.UnsafeGetStatus();
  207. }
  208. public void OnCompleted(Action<object> continuation, object state, short token)
  209. {
  210. core.OnCompleted(continuation, state, token);
  211. }
  212. public bool MoveNext()
  213. {
  214. if (cancellationToken.IsCancellationRequested)
  215. {
  216. core.TrySetCanceled(cancellationToken);
  217. return false;
  218. }
  219. core.TrySetResult(null);
  220. return false;
  221. }
  222. bool TryReturn()
  223. {
  224. TaskTracker.RemoveTracking(this);
  225. core.Reset();
  226. cancellationToken = default;
  227. return pool.TryPush(this);
  228. }
  229. }
  230. sealed class NextFramePromise : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode<NextFramePromise>
  231. {
  232. static TaskPool<NextFramePromise> pool;
  233. NextFramePromise nextNode;
  234. public ref NextFramePromise NextNode => ref nextNode;
  235. static NextFramePromise()
  236. {
  237. TaskPool.RegisterSizeGetter(typeof(NextFramePromise), () => pool.Size);
  238. }
  239. int frameCount;
  240. CancellationToken cancellationToken;
  241. UniTaskCompletionSourceCore<AsyncUnit> core;
  242. NextFramePromise()
  243. {
  244. }
  245. public static IUniTaskSource Create(PlayerLoopTiming timing, CancellationToken cancellationToken, out short token)
  246. {
  247. if (cancellationToken.IsCancellationRequested)
  248. {
  249. return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token);
  250. }
  251. if (!pool.TryPop(out var result))
  252. {
  253. result = new NextFramePromise();
  254. }
  255. result.frameCount = PlayerLoopHelper.IsMainThread ? Time.frameCount : -1;
  256. result.cancellationToken = cancellationToken;
  257. TaskTracker.TrackActiveTask(result, 3);
  258. PlayerLoopHelper.AddAction(timing, result);
  259. token = result.core.Version;
  260. return result;
  261. }
  262. public void GetResult(short token)
  263. {
  264. try
  265. {
  266. core.GetResult(token);
  267. }
  268. finally
  269. {
  270. TryReturn();
  271. }
  272. }
  273. public UniTaskStatus GetStatus(short token)
  274. {
  275. return core.GetStatus(token);
  276. }
  277. public UniTaskStatus UnsafeGetStatus()
  278. {
  279. return core.UnsafeGetStatus();
  280. }
  281. public void OnCompleted(Action<object> continuation, object state, short token)
  282. {
  283. core.OnCompleted(continuation, state, token);
  284. }
  285. public bool MoveNext()
  286. {
  287. if (cancellationToken.IsCancellationRequested)
  288. {
  289. core.TrySetCanceled(cancellationToken);
  290. return false;
  291. }
  292. if (frameCount == Time.frameCount)
  293. {
  294. return true;
  295. }
  296. core.TrySetResult(AsyncUnit.Default);
  297. return false;
  298. }
  299. bool TryReturn()
  300. {
  301. TaskTracker.RemoveTracking(this);
  302. core.Reset();
  303. cancellationToken = default;
  304. return pool.TryPush(this);
  305. }
  306. }
  307. sealed class WaitForEndOfFramePromise : IUniTaskSource, ITaskPoolNode<WaitForEndOfFramePromise>, System.Collections.IEnumerator
  308. {
  309. static TaskPool<WaitForEndOfFramePromise> pool;
  310. WaitForEndOfFramePromise nextNode;
  311. public ref WaitForEndOfFramePromise NextNode => ref nextNode;
  312. static WaitForEndOfFramePromise()
  313. {
  314. TaskPool.RegisterSizeGetter(typeof(WaitForEndOfFramePromise), () => pool.Size);
  315. }
  316. CancellationToken cancellationToken;
  317. UniTaskCompletionSourceCore<object> core;
  318. WaitForEndOfFramePromise()
  319. {
  320. }
  321. public static IUniTaskSource Create(MonoBehaviour coroutineRunner, CancellationToken cancellationToken, out short token)
  322. {
  323. if (cancellationToken.IsCancellationRequested)
  324. {
  325. return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token);
  326. }
  327. if (!pool.TryPop(out var result))
  328. {
  329. result = new WaitForEndOfFramePromise();
  330. }
  331. result.cancellationToken = cancellationToken;
  332. TaskTracker.TrackActiveTask(result, 3);
  333. coroutineRunner.StartCoroutine(result);
  334. token = result.core.Version;
  335. return result;
  336. }
  337. public void GetResult(short token)
  338. {
  339. try
  340. {
  341. core.GetResult(token);
  342. }
  343. finally
  344. {
  345. TryReturn();
  346. }
  347. }
  348. public UniTaskStatus GetStatus(short token)
  349. {
  350. return core.GetStatus(token);
  351. }
  352. public UniTaskStatus UnsafeGetStatus()
  353. {
  354. return core.UnsafeGetStatus();
  355. }
  356. public void OnCompleted(Action<object> continuation, object state, short token)
  357. {
  358. core.OnCompleted(continuation, state, token);
  359. }
  360. bool TryReturn()
  361. {
  362. TaskTracker.RemoveTracking(this);
  363. core.Reset();
  364. Reset(); // Reset Enumerator
  365. cancellationToken = default;
  366. return pool.TryPush(this);
  367. }
  368. // Coroutine Runner implementation
  369. static readonly WaitForEndOfFrame waitForEndOfFrameYieldInstruction = new WaitForEndOfFrame();
  370. bool isFirst = true;
  371. object IEnumerator.Current => waitForEndOfFrameYieldInstruction;
  372. bool IEnumerator.MoveNext()
  373. {
  374. if (isFirst)
  375. {
  376. isFirst = false;
  377. return true; // start WaitForEndOfFrame
  378. }
  379. if (cancellationToken.IsCancellationRequested)
  380. {
  381. core.TrySetCanceled(cancellationToken);
  382. return false;
  383. }
  384. core.TrySetResult(null);
  385. return false;
  386. }
  387. public void Reset()
  388. {
  389. isFirst = true;
  390. }
  391. }
  392. sealed class DelayFramePromise : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode<DelayFramePromise>
  393. {
  394. static TaskPool<DelayFramePromise> pool;
  395. DelayFramePromise nextNode;
  396. public ref DelayFramePromise NextNode => ref nextNode;
  397. static DelayFramePromise()
  398. {
  399. TaskPool.RegisterSizeGetter(typeof(DelayFramePromise), () => pool.Size);
  400. }
  401. int initialFrame;
  402. int delayFrameCount;
  403. CancellationToken cancellationToken;
  404. int currentFrameCount;
  405. UniTaskCompletionSourceCore<AsyncUnit> core;
  406. DelayFramePromise()
  407. {
  408. }
  409. public static IUniTaskSource Create(int delayFrameCount, PlayerLoopTiming timing, CancellationToken cancellationToken, out short token)
  410. {
  411. if (cancellationToken.IsCancellationRequested)
  412. {
  413. return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token);
  414. }
  415. if (!pool.TryPop(out var result))
  416. {
  417. result = new DelayFramePromise();
  418. }
  419. result.delayFrameCount = delayFrameCount;
  420. result.cancellationToken = cancellationToken;
  421. result.initialFrame = PlayerLoopHelper.IsMainThread ? Time.frameCount : -1;
  422. TaskTracker.TrackActiveTask(result, 3);
  423. PlayerLoopHelper.AddAction(timing, result);
  424. token = result.core.Version;
  425. return result;
  426. }
  427. public void GetResult(short token)
  428. {
  429. try
  430. {
  431. core.GetResult(token);
  432. }
  433. finally
  434. {
  435. TryReturn();
  436. }
  437. }
  438. public UniTaskStatus GetStatus(short token)
  439. {
  440. return core.GetStatus(token);
  441. }
  442. public UniTaskStatus UnsafeGetStatus()
  443. {
  444. return core.UnsafeGetStatus();
  445. }
  446. public void OnCompleted(Action<object> continuation, object state, short token)
  447. {
  448. core.OnCompleted(continuation, state, token);
  449. }
  450. public bool MoveNext()
  451. {
  452. if (cancellationToken.IsCancellationRequested)
  453. {
  454. core.TrySetCanceled(cancellationToken);
  455. return false;
  456. }
  457. if (currentFrameCount == 0)
  458. {
  459. if (delayFrameCount == 0) // same as Yield
  460. {
  461. core.TrySetResult(AsyncUnit.Default);
  462. return false;
  463. }
  464. // skip in initial frame.
  465. if (initialFrame == Time.frameCount)
  466. {
  467. #if UNITY_EDITOR
  468. // force use Realtime.
  469. if (PlayerLoopHelper.IsMainThread && !UnityEditor.EditorApplication.isPlaying)
  470. {
  471. //goto ++currentFrameCount
  472. }
  473. else
  474. {
  475. return true;
  476. }
  477. #else
  478. return true;
  479. #endif
  480. }
  481. }
  482. if (++currentFrameCount >= delayFrameCount)
  483. {
  484. core.TrySetResult(AsyncUnit.Default);
  485. return false;
  486. }
  487. return true;
  488. }
  489. bool TryReturn()
  490. {
  491. TaskTracker.RemoveTracking(this);
  492. core.Reset();
  493. currentFrameCount = default;
  494. delayFrameCount = default;
  495. cancellationToken = default;
  496. return pool.TryPush(this);
  497. }
  498. }
  499. sealed class DelayPromise : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode<DelayPromise>
  500. {
  501. static TaskPool<DelayPromise> pool;
  502. DelayPromise nextNode;
  503. public ref DelayPromise NextNode => ref nextNode;
  504. static DelayPromise()
  505. {
  506. TaskPool.RegisterSizeGetter(typeof(DelayPromise), () => pool.Size);
  507. }
  508. int initialFrame;
  509. float delayTimeSpan;
  510. float elapsed;
  511. CancellationToken cancellationToken;
  512. UniTaskCompletionSourceCore<object> core;
  513. DelayPromise()
  514. {
  515. }
  516. public static IUniTaskSource Create(TimeSpan delayTimeSpan, PlayerLoopTiming timing, CancellationToken cancellationToken, out short token)
  517. {
  518. if (cancellationToken.IsCancellationRequested)
  519. {
  520. return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token);
  521. }
  522. if (!pool.TryPop(out var result))
  523. {
  524. result = new DelayPromise();
  525. }
  526. result.elapsed = 0.0f;
  527. result.delayTimeSpan = (float)delayTimeSpan.TotalSeconds;
  528. result.cancellationToken = cancellationToken;
  529. result.initialFrame = PlayerLoopHelper.IsMainThread ? Time.frameCount : -1;
  530. TaskTracker.TrackActiveTask(result, 3);
  531. PlayerLoopHelper.AddAction(timing, result);
  532. token = result.core.Version;
  533. return result;
  534. }
  535. public void GetResult(short token)
  536. {
  537. try
  538. {
  539. core.GetResult(token);
  540. }
  541. finally
  542. {
  543. TryReturn();
  544. }
  545. }
  546. public UniTaskStatus GetStatus(short token)
  547. {
  548. return core.GetStatus(token);
  549. }
  550. public UniTaskStatus UnsafeGetStatus()
  551. {
  552. return core.UnsafeGetStatus();
  553. }
  554. public void OnCompleted(Action<object> continuation, object state, short token)
  555. {
  556. core.OnCompleted(continuation, state, token);
  557. }
  558. public bool MoveNext()
  559. {
  560. if (cancellationToken.IsCancellationRequested)
  561. {
  562. core.TrySetCanceled(cancellationToken);
  563. return false;
  564. }
  565. if (elapsed == 0.0f)
  566. {
  567. if (initialFrame == Time.frameCount)
  568. {
  569. return true;
  570. }
  571. }
  572. elapsed += Time.deltaTime;
  573. if (elapsed >= delayTimeSpan)
  574. {
  575. core.TrySetResult(null);
  576. return false;
  577. }
  578. return true;
  579. }
  580. bool TryReturn()
  581. {
  582. TaskTracker.RemoveTracking(this);
  583. core.Reset();
  584. delayTimeSpan = default;
  585. elapsed = default;
  586. cancellationToken = default;
  587. return pool.TryPush(this);
  588. }
  589. }
  590. sealed class DelayIgnoreTimeScalePromise : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode<DelayIgnoreTimeScalePromise>
  591. {
  592. static TaskPool<DelayIgnoreTimeScalePromise> pool;
  593. DelayIgnoreTimeScalePromise nextNode;
  594. public ref DelayIgnoreTimeScalePromise NextNode => ref nextNode;
  595. static DelayIgnoreTimeScalePromise()
  596. {
  597. TaskPool.RegisterSizeGetter(typeof(DelayIgnoreTimeScalePromise), () => pool.Size);
  598. }
  599. float delayFrameTimeSpan;
  600. float elapsed;
  601. int initialFrame;
  602. CancellationToken cancellationToken;
  603. UniTaskCompletionSourceCore<object> core;
  604. DelayIgnoreTimeScalePromise()
  605. {
  606. }
  607. public static IUniTaskSource Create(TimeSpan delayFrameTimeSpan, PlayerLoopTiming timing, CancellationToken cancellationToken, out short token)
  608. {
  609. if (cancellationToken.IsCancellationRequested)
  610. {
  611. return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token);
  612. }
  613. if (!pool.TryPop(out var result))
  614. {
  615. result = new DelayIgnoreTimeScalePromise();
  616. }
  617. result.elapsed = 0.0f;
  618. result.delayFrameTimeSpan = (float)delayFrameTimeSpan.TotalSeconds;
  619. result.initialFrame = PlayerLoopHelper.IsMainThread ? Time.frameCount : -1;
  620. result.cancellationToken = cancellationToken;
  621. TaskTracker.TrackActiveTask(result, 3);
  622. PlayerLoopHelper.AddAction(timing, result);
  623. token = result.core.Version;
  624. return result;
  625. }
  626. public void GetResult(short token)
  627. {
  628. try
  629. {
  630. core.GetResult(token);
  631. }
  632. finally
  633. {
  634. TryReturn();
  635. }
  636. }
  637. public UniTaskStatus GetStatus(short token)
  638. {
  639. return core.GetStatus(token);
  640. }
  641. public UniTaskStatus UnsafeGetStatus()
  642. {
  643. return core.UnsafeGetStatus();
  644. }
  645. public void OnCompleted(Action<object> continuation, object state, short token)
  646. {
  647. core.OnCompleted(continuation, state, token);
  648. }
  649. public bool MoveNext()
  650. {
  651. if (cancellationToken.IsCancellationRequested)
  652. {
  653. core.TrySetCanceled(cancellationToken);
  654. return false;
  655. }
  656. if (elapsed == 0.0f)
  657. {
  658. if (initialFrame == Time.frameCount)
  659. {
  660. return true;
  661. }
  662. }
  663. elapsed += Time.unscaledDeltaTime;
  664. if (elapsed >= delayFrameTimeSpan)
  665. {
  666. core.TrySetResult(null);
  667. return false;
  668. }
  669. return true;
  670. }
  671. bool TryReturn()
  672. {
  673. TaskTracker.RemoveTracking(this);
  674. core.Reset();
  675. delayFrameTimeSpan = default;
  676. elapsed = default;
  677. cancellationToken = default;
  678. return pool.TryPush(this);
  679. }
  680. }
  681. sealed class DelayRealtimePromise : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode<DelayRealtimePromise>
  682. {
  683. static TaskPool<DelayRealtimePromise> pool;
  684. DelayRealtimePromise nextNode;
  685. public ref DelayRealtimePromise NextNode => ref nextNode;
  686. static DelayRealtimePromise()
  687. {
  688. TaskPool.RegisterSizeGetter(typeof(DelayRealtimePromise), () => pool.Size);
  689. }
  690. long delayTimeSpanTicks;
  691. ValueStopwatch stopwatch;
  692. CancellationToken cancellationToken;
  693. UniTaskCompletionSourceCore<AsyncUnit> core;
  694. DelayRealtimePromise()
  695. {
  696. }
  697. public static IUniTaskSource Create(TimeSpan delayTimeSpan, PlayerLoopTiming timing, CancellationToken cancellationToken, out short token)
  698. {
  699. if (cancellationToken.IsCancellationRequested)
  700. {
  701. return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token);
  702. }
  703. if (!pool.TryPop(out var result))
  704. {
  705. result = new DelayRealtimePromise();
  706. }
  707. result.stopwatch = ValueStopwatch.StartNew();
  708. result.delayTimeSpanTicks = delayTimeSpan.Ticks;
  709. result.cancellationToken = cancellationToken;
  710. TaskTracker.TrackActiveTask(result, 3);
  711. PlayerLoopHelper.AddAction(timing, result);
  712. token = result.core.Version;
  713. return result;
  714. }
  715. public void GetResult(short token)
  716. {
  717. try
  718. {
  719. core.GetResult(token);
  720. }
  721. finally
  722. {
  723. TryReturn();
  724. }
  725. }
  726. public UniTaskStatus GetStatus(short token)
  727. {
  728. return core.GetStatus(token);
  729. }
  730. public UniTaskStatus UnsafeGetStatus()
  731. {
  732. return core.UnsafeGetStatus();
  733. }
  734. public void OnCompleted(Action<object> continuation, object state, short token)
  735. {
  736. core.OnCompleted(continuation, state, token);
  737. }
  738. public bool MoveNext()
  739. {
  740. if (cancellationToken.IsCancellationRequested)
  741. {
  742. core.TrySetCanceled(cancellationToken);
  743. return false;
  744. }
  745. if (stopwatch.IsInvalid)
  746. {
  747. core.TrySetResult(AsyncUnit.Default);
  748. return false;
  749. }
  750. if (stopwatch.ElapsedTicks >= delayTimeSpanTicks)
  751. {
  752. core.TrySetResult(AsyncUnit.Default);
  753. return false;
  754. }
  755. return true;
  756. }
  757. bool TryReturn()
  758. {
  759. TaskTracker.RemoveTracking(this);
  760. core.Reset();
  761. stopwatch = default;
  762. cancellationToken = default;
  763. return pool.TryPush(this);
  764. }
  765. }
  766. }
  767. public readonly struct YieldAwaitable
  768. {
  769. readonly PlayerLoopTiming timing;
  770. public YieldAwaitable(PlayerLoopTiming timing)
  771. {
  772. this.timing = timing;
  773. }
  774. public Awaiter GetAwaiter()
  775. {
  776. return new Awaiter(timing);
  777. }
  778. public UniTask ToUniTask()
  779. {
  780. return UniTask.Yield(timing, CancellationToken.None);
  781. }
  782. public readonly struct Awaiter : ICriticalNotifyCompletion
  783. {
  784. readonly PlayerLoopTiming timing;
  785. public Awaiter(PlayerLoopTiming timing)
  786. {
  787. this.timing = timing;
  788. }
  789. public bool IsCompleted => false;
  790. public void GetResult() { }
  791. public void OnCompleted(Action continuation)
  792. {
  793. PlayerLoopHelper.AddContinuation(timing, continuation);
  794. }
  795. public void UnsafeOnCompleted(Action continuation)
  796. {
  797. PlayerLoopHelper.AddContinuation(timing, continuation);
  798. }
  799. }
  800. }
  801. }