UniTask.Factory.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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.Runtime.CompilerServices;
  5. using System.Runtime.ExceptionServices;
  6. using System.Threading;
  7. namespace Cysharp.Threading.Tasks
  8. {
  9. public partial struct UniTask
  10. {
  11. static readonly UniTask CanceledUniTask = new Func<UniTask>(() =>
  12. {
  13. return new UniTask(new CanceledResultSource(CancellationToken.None), 0);
  14. })();
  15. static class CanceledUniTaskCache<T>
  16. {
  17. public static readonly UniTask<T> Task;
  18. static CanceledUniTaskCache()
  19. {
  20. Task = new UniTask<T>(new CanceledResultSource<T>(CancellationToken.None), 0);
  21. }
  22. }
  23. public static readonly UniTask CompletedTask = new UniTask();
  24. public static UniTask FromException(Exception ex)
  25. {
  26. if (ex is OperationCanceledException oce)
  27. {
  28. return FromCanceled(oce.CancellationToken);
  29. }
  30. return new UniTask(new ExceptionResultSource(ex), 0);
  31. }
  32. public static UniTask<T> FromException<T>(Exception ex)
  33. {
  34. if (ex is OperationCanceledException oce)
  35. {
  36. return FromCanceled<T>(oce.CancellationToken);
  37. }
  38. return new UniTask<T>(new ExceptionResultSource<T>(ex), 0);
  39. }
  40. public static UniTask<T> FromResult<T>(T value)
  41. {
  42. return new UniTask<T>(value);
  43. }
  44. public static UniTask FromCanceled(CancellationToken cancellationToken = default)
  45. {
  46. if (cancellationToken == CancellationToken.None)
  47. {
  48. return CanceledUniTask;
  49. }
  50. else
  51. {
  52. return new UniTask(new CanceledResultSource(cancellationToken), 0);
  53. }
  54. }
  55. public static UniTask<T> FromCanceled<T>(CancellationToken cancellationToken = default)
  56. {
  57. if (cancellationToken == CancellationToken.None)
  58. {
  59. return CanceledUniTaskCache<T>.Task;
  60. }
  61. else
  62. {
  63. return new UniTask<T>(new CanceledResultSource<T>(cancellationToken), 0);
  64. }
  65. }
  66. public static UniTask Create(Func<UniTask> factory)
  67. {
  68. return factory();
  69. }
  70. public static UniTask<T> Create<T>(Func<UniTask<T>> factory)
  71. {
  72. return factory();
  73. }
  74. public static AsyncLazy Lazy(Func<UniTask> factory)
  75. {
  76. return new AsyncLazy(factory);
  77. }
  78. public static AsyncLazy<T> Lazy<T>(Func<UniTask<T>> factory)
  79. {
  80. return new AsyncLazy<T>(factory);
  81. }
  82. /// <summary>
  83. /// helper of fire and forget void action.
  84. /// </summary>
  85. public static void Void(Func<UniTaskVoid> asyncAction)
  86. {
  87. asyncAction().Forget();
  88. }
  89. /// <summary>
  90. /// helper of fire and forget void action.
  91. /// </summary>
  92. public static void Void(Func<CancellationToken, UniTaskVoid> asyncAction, CancellationToken cancellationToken)
  93. {
  94. asyncAction(cancellationToken).Forget();
  95. }
  96. /// <summary>
  97. /// helper of fire and forget void action.
  98. /// </summary>
  99. public static void Void<T>(Func<T, UniTaskVoid> asyncAction, T state)
  100. {
  101. asyncAction(state).Forget();
  102. }
  103. /// <summary>
  104. /// helper of create add UniTaskVoid to delegate.
  105. /// For example: FooAction = UniTask.Action(async () => { /* */ })
  106. /// </summary>
  107. public static Action Action(Func<UniTaskVoid> asyncAction)
  108. {
  109. return () => asyncAction().Forget();
  110. }
  111. /// <summary>
  112. /// helper of create add UniTaskVoid to delegate.
  113. /// </summary>
  114. public static Action Action(Func<CancellationToken, UniTaskVoid> asyncAction, CancellationToken cancellationToken)
  115. {
  116. return () => asyncAction(cancellationToken).Forget();
  117. }
  118. #if UNITY_2018_3_OR_NEWER
  119. /// <summary>
  120. /// Create async void(UniTaskVoid) UnityAction.
  121. /// For exampe: onClick.AddListener(UniTask.UnityAction(async () => { /* */ } ))
  122. /// </summary>
  123. public static UnityEngine.Events.UnityAction UnityAction(Func<UniTaskVoid> asyncAction)
  124. {
  125. return () => asyncAction().Forget();
  126. }
  127. /// <summary>
  128. /// Create async void(UniTaskVoid) UnityAction.
  129. /// For exampe: onClick.AddListener(UniTask.UnityAction(FooAsync, this.GetCancellationTokenOnDestroy()))
  130. /// </summary>
  131. public static UnityEngine.Events.UnityAction UnityAction(Func<CancellationToken, UniTaskVoid> asyncAction, CancellationToken cancellationToken)
  132. {
  133. return () => asyncAction(cancellationToken).Forget();
  134. }
  135. #endif
  136. /// <summary>
  137. /// Defer the task creation just before call await.
  138. /// </summary>
  139. public static UniTask Defer(Func<UniTask> factory)
  140. {
  141. return new UniTask(new DeferPromise(factory), 0);
  142. }
  143. /// <summary>
  144. /// Defer the task creation just before call await.
  145. /// </summary>
  146. public static UniTask<T> Defer<T>(Func<UniTask<T>> factory)
  147. {
  148. return new UniTask<T>(new DeferPromise<T>(factory), 0);
  149. }
  150. /// <summary>
  151. /// Never complete.
  152. /// </summary>
  153. public static UniTask Never(CancellationToken cancellationToken)
  154. {
  155. return new UniTask<AsyncUnit>(new NeverPromise<AsyncUnit>(cancellationToken), 0);
  156. }
  157. /// <summary>
  158. /// Never complete.
  159. /// </summary>
  160. public static UniTask<T> Never<T>(CancellationToken cancellationToken)
  161. {
  162. return new UniTask<T>(new NeverPromise<T>(cancellationToken), 0);
  163. }
  164. sealed class ExceptionResultSource : IUniTaskSource
  165. {
  166. readonly ExceptionDispatchInfo exception;
  167. bool calledGet;
  168. public ExceptionResultSource(Exception exception)
  169. {
  170. this.exception = ExceptionDispatchInfo.Capture(exception);
  171. }
  172. public void GetResult(short token)
  173. {
  174. if (!calledGet)
  175. {
  176. calledGet = true;
  177. GC.SuppressFinalize(this);
  178. }
  179. exception.Throw();
  180. }
  181. public UniTaskStatus GetStatus(short token)
  182. {
  183. return UniTaskStatus.Faulted;
  184. }
  185. public UniTaskStatus UnsafeGetStatus()
  186. {
  187. return UniTaskStatus.Faulted;
  188. }
  189. public void OnCompleted(Action<object> continuation, object state, short token)
  190. {
  191. continuation(state);
  192. }
  193. ~ExceptionResultSource()
  194. {
  195. if (!calledGet)
  196. {
  197. UniTaskScheduler.PublishUnobservedTaskException(exception.SourceException);
  198. }
  199. }
  200. }
  201. sealed class ExceptionResultSource<T> : IUniTaskSource<T>
  202. {
  203. readonly ExceptionDispatchInfo exception;
  204. bool calledGet;
  205. public ExceptionResultSource(Exception exception)
  206. {
  207. this.exception = ExceptionDispatchInfo.Capture(exception);
  208. }
  209. public T GetResult(short token)
  210. {
  211. if (!calledGet)
  212. {
  213. calledGet = true;
  214. GC.SuppressFinalize(this);
  215. }
  216. exception.Throw();
  217. return default;
  218. }
  219. void IUniTaskSource.GetResult(short token)
  220. {
  221. if (!calledGet)
  222. {
  223. calledGet = true;
  224. GC.SuppressFinalize(this);
  225. }
  226. exception.Throw();
  227. }
  228. public UniTaskStatus GetStatus(short token)
  229. {
  230. return UniTaskStatus.Faulted;
  231. }
  232. public UniTaskStatus UnsafeGetStatus()
  233. {
  234. return UniTaskStatus.Faulted;
  235. }
  236. public void OnCompleted(Action<object> continuation, object state, short token)
  237. {
  238. continuation(state);
  239. }
  240. ~ExceptionResultSource()
  241. {
  242. if (!calledGet)
  243. {
  244. UniTaskScheduler.PublishUnobservedTaskException(exception.SourceException);
  245. }
  246. }
  247. }
  248. sealed class CanceledResultSource : IUniTaskSource
  249. {
  250. readonly CancellationToken cancellationToken;
  251. public CanceledResultSource(CancellationToken cancellationToken)
  252. {
  253. this.cancellationToken = cancellationToken;
  254. }
  255. public void GetResult(short token)
  256. {
  257. throw new OperationCanceledException(cancellationToken);
  258. }
  259. public UniTaskStatus GetStatus(short token)
  260. {
  261. return UniTaskStatus.Canceled;
  262. }
  263. public UniTaskStatus UnsafeGetStatus()
  264. {
  265. return UniTaskStatus.Canceled;
  266. }
  267. public void OnCompleted(Action<object> continuation, object state, short token)
  268. {
  269. continuation(state);
  270. }
  271. }
  272. sealed class CanceledResultSource<T> : IUniTaskSource<T>
  273. {
  274. readonly CancellationToken cancellationToken;
  275. public CanceledResultSource(CancellationToken cancellationToken)
  276. {
  277. this.cancellationToken = cancellationToken;
  278. }
  279. public T GetResult(short token)
  280. {
  281. throw new OperationCanceledException(cancellationToken);
  282. }
  283. void IUniTaskSource.GetResult(short token)
  284. {
  285. throw new OperationCanceledException(cancellationToken);
  286. }
  287. public UniTaskStatus GetStatus(short token)
  288. {
  289. return UniTaskStatus.Canceled;
  290. }
  291. public UniTaskStatus UnsafeGetStatus()
  292. {
  293. return UniTaskStatus.Canceled;
  294. }
  295. public void OnCompleted(Action<object> continuation, object state, short token)
  296. {
  297. continuation(state);
  298. }
  299. }
  300. sealed class DeferPromise : IUniTaskSource
  301. {
  302. Func<UniTask> factory;
  303. UniTask task;
  304. UniTask.Awaiter awaiter;
  305. public DeferPromise(Func<UniTask> factory)
  306. {
  307. this.factory = factory;
  308. }
  309. public void GetResult(short token)
  310. {
  311. awaiter.GetResult();
  312. }
  313. public UniTaskStatus GetStatus(short token)
  314. {
  315. var f = Interlocked.Exchange(ref factory, null);
  316. if (f != null)
  317. {
  318. task = f();
  319. awaiter = task.GetAwaiter();
  320. }
  321. return task.Status;
  322. }
  323. public void OnCompleted(Action<object> continuation, object state, short token)
  324. {
  325. awaiter.SourceOnCompleted(continuation, state);
  326. }
  327. public UniTaskStatus UnsafeGetStatus()
  328. {
  329. return task.Status;
  330. }
  331. }
  332. sealed class DeferPromise<T> : IUniTaskSource<T>
  333. {
  334. Func<UniTask<T>> factory;
  335. UniTask<T> task;
  336. UniTask<T>.Awaiter awaiter;
  337. public DeferPromise(Func<UniTask<T>> factory)
  338. {
  339. this.factory = factory;
  340. }
  341. public T GetResult(short token)
  342. {
  343. return awaiter.GetResult();
  344. }
  345. void IUniTaskSource.GetResult(short token)
  346. {
  347. awaiter.GetResult();
  348. }
  349. public UniTaskStatus GetStatus(short token)
  350. {
  351. var f = Interlocked.Exchange(ref factory, null);
  352. if (f != null)
  353. {
  354. task = f();
  355. awaiter = task.GetAwaiter();
  356. }
  357. return task.Status;
  358. }
  359. public void OnCompleted(Action<object> continuation, object state, short token)
  360. {
  361. awaiter.SourceOnCompleted(continuation, state);
  362. }
  363. public UniTaskStatus UnsafeGetStatus()
  364. {
  365. return task.Status;
  366. }
  367. }
  368. sealed class NeverPromise<T> : IUniTaskSource<T>
  369. {
  370. static readonly Action<object> cancellationCallback = CancellationCallback;
  371. CancellationToken cancellationToken;
  372. UniTaskCompletionSourceCore<T> core;
  373. public NeverPromise(CancellationToken cancellationToken)
  374. {
  375. this.cancellationToken = cancellationToken;
  376. if (this.cancellationToken.CanBeCanceled)
  377. {
  378. this.cancellationToken.RegisterWithoutCaptureExecutionContext(cancellationCallback, this);
  379. }
  380. }
  381. static void CancellationCallback(object state)
  382. {
  383. var self = (NeverPromise<T>)state;
  384. self.core.TrySetCanceled(self.cancellationToken);
  385. }
  386. public T GetResult(short token)
  387. {
  388. return core.GetResult(token);
  389. }
  390. public UniTaskStatus GetStatus(short token)
  391. {
  392. return core.GetStatus(token);
  393. }
  394. public UniTaskStatus UnsafeGetStatus()
  395. {
  396. return core.UnsafeGetStatus();
  397. }
  398. public void OnCompleted(Action<object> continuation, object state, short token)
  399. {
  400. core.OnCompleted(continuation, state, token);
  401. }
  402. void IUniTaskSource.GetResult(short token)
  403. {
  404. core.GetResult(token);
  405. }
  406. }
  407. }
  408. internal static class CompletedTasks
  409. {
  410. public static readonly UniTask<AsyncUnit> AsyncUnit = UniTask.FromResult(Cysharp.Threading.Tasks.AsyncUnit.Default);
  411. public static readonly UniTask<bool> True = UniTask.FromResult(true);
  412. public static readonly UniTask<bool> False = UniTask.FromResult(false);
  413. public static readonly UniTask<int> Zero = UniTask.FromResult(0);
  414. public static readonly UniTask<int> MinusOne = UniTask.FromResult(-1);
  415. public static readonly UniTask<int> One = UniTask.FromResult(1);
  416. }
  417. }