UnityAsyncExtensions.tt 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. <#@ template debug="false" hostspecific="false" language="C#" #>
  2. <#@ assembly name="System.Core" #>
  3. <#@ import namespace="System.Linq" #>
  4. <#@ import namespace="System.Text" #>
  5. <#@ import namespace="System.Collections.Generic" #>
  6. <#@ output extension=".cs" #>
  7. <#
  8. var types = new (string typeName, string returnType, string returnField)[]
  9. {
  10. ("AsyncOperation", "void", null),
  11. ("ResourceRequest", "UnityEngine.Object", "asset"),
  12. ("AssetBundleRequest", "UnityEngine.Object", "asset"), // allAssets?
  13. ("AssetBundleCreateRequest", "AssetBundle", "assetBundle"),
  14. ("UnityWebRequestAsyncOperation", "UnityWebRequest", "webRequest") // -> #if ENABLE_UNITYWEBREQUEST && (!UNITY_2019_1_OR_NEWER || UNITASK_WEBREQUEST_SUPPORT)
  15. };
  16. Func<string, string> ToUniTaskReturnType = x => (x == "void") ? "UniTask" : $"UniTask<{x}>";
  17. Func<string, string> ToIUniTaskSourceReturnType = x => (x == "void") ? "IUniTaskSource" : $"IUniTaskSource<{x}>";
  18. Func<(string typeName, string returnType, string returnField), bool> IsAsyncOperationBase = x => x.typeName == "AsyncOperation";
  19. Func<(string typeName, string returnType, string returnField), bool> IsUnityWebRequest = x => x.returnType == "UnityWebRequest";
  20. Func<(string typeName, string returnType, string returnField), bool> IsAssetBundleModule = x => x.typeName == "AssetBundleRequest" || x.typeName == "AssetBundleCreateRequest";
  21. Func<(string typeName, string returnType, string returnField), bool> IsVoid = x => x.returnType == "void";
  22. #>
  23. #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
  24. using System;
  25. using System.Runtime.CompilerServices;
  26. using System.Threading;
  27. using UnityEngine;
  28. using Cysharp.Threading.Tasks.Internal;
  29. #if ENABLE_UNITYWEBREQUEST && (!UNITY_2019_1_OR_NEWER || UNITASK_WEBREQUEST_SUPPORT)
  30. using UnityEngine.Networking;
  31. #endif
  32. namespace Cysharp.Threading.Tasks
  33. {
  34. public static partial class UnityAsyncExtensions
  35. {
  36. <# foreach(var t in types) { #>
  37. <# if(IsUnityWebRequest(t)) { #>
  38. #if ENABLE_UNITYWEBREQUEST && (!UNITY_2019_1_OR_NEWER || UNITASK_WEBREQUEST_SUPPORT)
  39. <# } else if(IsAssetBundleModule(t)) { #>
  40. #if UNITASK_ASSETBUNDLE_SUPPORT
  41. <# } #>
  42. #region <#= t.typeName #>
  43. <# if (IsAsyncOperationBase(t)) { #>
  44. #if !UNITY_2023_1_OR_NEWER
  45. // from Unity2023.1.0a15, AsyncOperationAwaitableExtensions.GetAwaiter is defined in UnityEngine.
  46. <# } #>
  47. public static <#= t.typeName #>Awaiter GetAwaiter(this <#= t.typeName #> asyncOperation)
  48. {
  49. Error.ThrowArgumentNullException(asyncOperation, nameof(asyncOperation));
  50. return new <#= t.typeName #>Awaiter(asyncOperation);
  51. }
  52. <# if (IsAsyncOperationBase(t)) { #>
  53. #endif
  54. <# } #>
  55. public static <#= ToUniTaskReturnType(t.returnType) #> WithCancellation(this <#= t.typeName #> asyncOperation, CancellationToken cancellationToken)
  56. {
  57. return ToUniTask(asyncOperation, cancellationToken: cancellationToken);
  58. }
  59. public static <#= ToUniTaskReturnType(t.returnType) #> WithCancellation(this <#= t.typeName #> asyncOperation, CancellationToken cancellationToken, bool cancelImmediately)
  60. {
  61. return ToUniTask(asyncOperation, cancellationToken: cancellationToken, cancelImmediately: cancelImmediately);
  62. }
  63. public static <#= ToUniTaskReturnType(t.returnType) #> ToUniTask(this <#= t.typeName #> asyncOperation, IProgress<float> progress = null, PlayerLoopTiming timing = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false)
  64. {
  65. Error.ThrowArgumentNullException(asyncOperation, nameof(asyncOperation));
  66. if (cancellationToken.IsCancellationRequested) return UniTask.FromCanceled<#= IsVoid(t) ? "" : "<" + t.returnType + ">" #>(cancellationToken);
  67. <# if(IsUnityWebRequest(t)) { #>
  68. if (asyncOperation.isDone)
  69. {
  70. if (asyncOperation.webRequest.IsError())
  71. {
  72. return UniTask.FromException<UnityWebRequest>(new UnityWebRequestException(asyncOperation.webRequest));
  73. }
  74. return UniTask.FromResult(asyncOperation.webRequest);
  75. }
  76. <# } else { #>
  77. if (asyncOperation.isDone) return <#= IsVoid(t) ? "UniTask.CompletedTask" : $"UniTask.FromResult(asyncOperation.{t.returnField})" #>;
  78. <# } #>
  79. return new <#= ToUniTaskReturnType(t.returnType) #>(<#= t.typeName #>ConfiguredSource.Create(asyncOperation, timing, progress, cancellationToken, cancelImmediately, out var token), token);
  80. }
  81. public struct <#= t.typeName #>Awaiter : ICriticalNotifyCompletion
  82. {
  83. <#= t.typeName #> asyncOperation;
  84. Action<AsyncOperation> continuationAction;
  85. public <#= t.typeName #>Awaiter(<#= t.typeName #> asyncOperation)
  86. {
  87. this.asyncOperation = asyncOperation;
  88. this.continuationAction = null;
  89. }
  90. public bool IsCompleted => asyncOperation.isDone;
  91. public <#= t.returnType #> GetResult()
  92. {
  93. if (continuationAction != null)
  94. {
  95. asyncOperation.completed -= continuationAction;
  96. continuationAction = null;
  97. <# if (!IsVoid(t)) { #>
  98. var result = <#= $"asyncOperation.{t.returnField}" #>;
  99. asyncOperation = null;
  100. <# if(IsUnityWebRequest(t)) { #>
  101. if (result.IsError())
  102. {
  103. throw new UnityWebRequestException(result);
  104. }
  105. <# } #>
  106. return result;
  107. <# } else { #>
  108. asyncOperation = null;
  109. <# } #>
  110. }
  111. else
  112. {
  113. <# if (!IsVoid(t)) { #>
  114. var result = <#= $"asyncOperation.{t.returnField}" #>;
  115. asyncOperation = null;
  116. <# if(IsUnityWebRequest(t)) { #>
  117. if (result.IsError())
  118. {
  119. throw new UnityWebRequestException(result);
  120. }
  121. <# } #>
  122. return result;
  123. <# } else { #>
  124. asyncOperation = null;
  125. <# } #>
  126. }
  127. }
  128. public void OnCompleted(Action continuation)
  129. {
  130. UnsafeOnCompleted(continuation);
  131. }
  132. public void UnsafeOnCompleted(Action continuation)
  133. {
  134. Error.ThrowWhenContinuationIsAlreadyRegistered(continuationAction);
  135. continuationAction = PooledDelegate<AsyncOperation>.Create(continuation);
  136. asyncOperation.completed += continuationAction;
  137. }
  138. }
  139. sealed class <#= t.typeName #>ConfiguredSource : <#= ToIUniTaskSourceReturnType(t.returnType) #>, IPlayerLoopItem, ITaskPoolNode<<#= t.typeName #>ConfiguredSource>
  140. {
  141. static TaskPool<<#= t.typeName #>ConfiguredSource> pool;
  142. <#= t.typeName #>ConfiguredSource nextNode;
  143. public ref <#= t.typeName #>ConfiguredSource NextNode => ref nextNode;
  144. static <#= t.typeName #>ConfiguredSource()
  145. {
  146. TaskPool.RegisterSizeGetter(typeof(<#= t.typeName #>ConfiguredSource), () => pool.Size);
  147. }
  148. <#= t.typeName #> asyncOperation;
  149. IProgress<float> progress;
  150. CancellationToken cancellationToken;
  151. CancellationTokenRegistration cancellationTokenRegistration;
  152. bool cancelImmediately;
  153. bool completed;
  154. UniTaskCompletionSourceCore<<#= IsVoid(t) ? "AsyncUnit" : t.returnType #>> core;
  155. Action<AsyncOperation> continuationAction;
  156. <#= t.typeName #>ConfiguredSource()
  157. {
  158. continuationAction = Continuation;
  159. }
  160. public static <#= ToIUniTaskSourceReturnType(t.returnType) #> Create(<#= t.typeName #> asyncOperation, PlayerLoopTiming timing, IProgress<float> progress, CancellationToken cancellationToken, bool cancelImmediately, out short token)
  161. {
  162. if (cancellationToken.IsCancellationRequested)
  163. {
  164. return AutoResetUniTaskCompletionSource<#= IsVoid(t) ? "" : $"<{t.returnType}>" #>.CreateFromCanceled(cancellationToken, out token);
  165. }
  166. if (!pool.TryPop(out var result))
  167. {
  168. result = new <#= t.typeName #>ConfiguredSource();
  169. }
  170. result.asyncOperation = asyncOperation;
  171. result.progress = progress;
  172. result.cancellationToken = cancellationToken;
  173. result.cancelImmediately = cancelImmediately;
  174. result.completed = false;
  175. asyncOperation.completed += result.continuationAction;
  176. if (cancelImmediately && cancellationToken.CanBeCanceled)
  177. {
  178. result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state =>
  179. {
  180. var source = (<#= t.typeName #>ConfiguredSource)state;
  181. <# if(IsUnityWebRequest(t)) { #>
  182. source.asyncOperation.webRequest.Abort();
  183. <# } #>
  184. source.core.TrySetCanceled(source.cancellationToken);
  185. }, result);
  186. }
  187. TaskTracker.TrackActiveTask(result, 3);
  188. PlayerLoopHelper.AddAction(timing, result);
  189. token = result.core.Version;
  190. return result;
  191. }
  192. public <#= t.returnType #> GetResult(short token)
  193. {
  194. try
  195. {
  196. <# if (!IsVoid(t)) { #>
  197. return core.GetResult(token);
  198. <# } else { #>
  199. core.GetResult(token);
  200. <# } #>
  201. }
  202. finally
  203. {
  204. if (!(cancelImmediately && cancellationToken.IsCancellationRequested))
  205. {
  206. TryReturn();
  207. }
  208. }
  209. }
  210. <# if (!IsVoid(t)) { #>
  211. void IUniTaskSource.GetResult(short token)
  212. {
  213. GetResult(token);
  214. }
  215. <# } #>
  216. public UniTaskStatus GetStatus(short token)
  217. {
  218. return core.GetStatus(token);
  219. }
  220. public UniTaskStatus UnsafeGetStatus()
  221. {
  222. return core.UnsafeGetStatus();
  223. }
  224. public void OnCompleted(Action<object> continuation, object state, short token)
  225. {
  226. core.OnCompleted(continuation, state, token);
  227. }
  228. public bool MoveNext()
  229. {
  230. // Already completed
  231. if (completed || asyncOperation == null)
  232. {
  233. return false;
  234. }
  235. if (cancellationToken.IsCancellationRequested)
  236. {
  237. <# if(IsUnityWebRequest(t)) { #>
  238. asyncOperation.webRequest.Abort();
  239. <# } #>
  240. core.TrySetCanceled(cancellationToken);
  241. return false;
  242. }
  243. if (progress != null)
  244. {
  245. progress.Report(asyncOperation.progress);
  246. }
  247. if (asyncOperation.isDone)
  248. {
  249. <# if(IsUnityWebRequest(t)) { #>
  250. if (asyncOperation.webRequest.IsError())
  251. {
  252. core.TrySetException(new UnityWebRequestException(asyncOperation.webRequest));
  253. }
  254. else
  255. {
  256. core.TrySetResult(asyncOperation.webRequest);
  257. }
  258. <# } else { #>
  259. core.TrySetResult(<#= IsVoid(t) ? "AsyncUnit.Default" : $"asyncOperation.{t.returnField}" #>);
  260. <# } #>
  261. return false;
  262. }
  263. return true;
  264. }
  265. bool TryReturn()
  266. {
  267. TaskTracker.RemoveTracking(this);
  268. core.Reset();
  269. asyncOperation.completed -= continuationAction;
  270. asyncOperation = default;
  271. progress = default;
  272. cancellationToken = default;
  273. cancellationTokenRegistration.Dispose();
  274. cancelImmediately = default;
  275. return pool.TryPush(this);
  276. }
  277. void Continuation(AsyncOperation _)
  278. {
  279. if (completed)
  280. {
  281. return;
  282. }
  283. completed = true;
  284. if (cancellationToken.IsCancellationRequested)
  285. {
  286. core.TrySetCanceled(cancellationToken);
  287. }
  288. <# if(IsUnityWebRequest(t)) { #>
  289. else if (asyncOperation.webRequest.IsError())
  290. {
  291. core.TrySetException(new UnityWebRequestException(asyncOperation.webRequest));
  292. }
  293. else
  294. {
  295. core.TrySetResult(asyncOperation.webRequest);
  296. }
  297. <# } else { #>
  298. else
  299. {
  300. core.TrySetResult(<#= IsVoid(t) ? "AsyncUnit.Default" : $"asyncOperation.{t.returnField}" #>);
  301. }
  302. <# } #>
  303. }
  304. }
  305. #endregion
  306. <# if(IsUnityWebRequest(t) || IsAssetBundleModule(t)) { #>
  307. #endif
  308. <# } #>
  309. <# } #>
  310. }
  311. }