StateMachineRunner.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. #pragma warning disable CS1591
  2. using Cysharp.Threading.Tasks.Internal;
  3. using System;
  4. using System.Linq;
  5. using System.Diagnostics;
  6. using System.Runtime.CompilerServices;
  7. namespace Cysharp.Threading.Tasks.CompilerServices
  8. {
  9. // #ENABLE_IL2CPP in this file is to avoid bug of IL2CPP VM.
  10. // Issue is tracked on https://issuetracker.unity3d.com/issues/il2cpp-incorrect-results-when-calling-a-method-from-outside-class-in-a-struct
  11. // but currently it is labeled `Won't Fix`.
  12. internal interface IStateMachineRunner
  13. {
  14. Action MoveNext { get; }
  15. void Return();
  16. #if ENABLE_IL2CPP
  17. Action ReturnAction { get; }
  18. #endif
  19. }
  20. internal interface IStateMachineRunnerPromise : IUniTaskSource
  21. {
  22. Action MoveNext { get; }
  23. UniTask Task { get; }
  24. void SetResult();
  25. void SetException(Exception exception);
  26. }
  27. internal interface IStateMachineRunnerPromise<T> : IUniTaskSource<T>
  28. {
  29. Action MoveNext { get; }
  30. UniTask<T> Task { get; }
  31. void SetResult(T result);
  32. void SetException(Exception exception);
  33. }
  34. internal static class StateMachineUtility
  35. {
  36. // Get AsyncStateMachine internal state to check IL2CPP bug
  37. public static int GetState(IAsyncStateMachine stateMachine)
  38. {
  39. var info = stateMachine.GetType().GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
  40. .First(x => x.Name.EndsWith("__state"));
  41. return (int)info.GetValue(stateMachine);
  42. }
  43. }
  44. internal sealed class AsyncUniTaskVoid<TStateMachine> : IStateMachineRunner, ITaskPoolNode<AsyncUniTaskVoid<TStateMachine>>, IUniTaskSource
  45. where TStateMachine : IAsyncStateMachine
  46. {
  47. static TaskPool<AsyncUniTaskVoid<TStateMachine>> pool;
  48. #if ENABLE_IL2CPP
  49. public Action ReturnAction { get; }
  50. #endif
  51. TStateMachine stateMachine;
  52. public Action MoveNext { get; }
  53. public AsyncUniTaskVoid()
  54. {
  55. MoveNext = Run;
  56. #if ENABLE_IL2CPP
  57. ReturnAction = Return;
  58. #endif
  59. }
  60. public static void SetStateMachine(ref TStateMachine stateMachine, ref IStateMachineRunner runnerFieldRef)
  61. {
  62. if (!pool.TryPop(out var result))
  63. {
  64. result = new AsyncUniTaskVoid<TStateMachine>();
  65. }
  66. TaskTracker.TrackActiveTask(result, 3);
  67. runnerFieldRef = result; // set runner before copied.
  68. result.stateMachine = stateMachine; // copy struct StateMachine(in release build).
  69. }
  70. static AsyncUniTaskVoid()
  71. {
  72. TaskPool.RegisterSizeGetter(typeof(AsyncUniTaskVoid<TStateMachine>), () => pool.Size);
  73. }
  74. AsyncUniTaskVoid<TStateMachine> nextNode;
  75. public ref AsyncUniTaskVoid<TStateMachine> NextNode => ref nextNode;
  76. public void Return()
  77. {
  78. TaskTracker.RemoveTracking(this);
  79. stateMachine = default;
  80. pool.TryPush(this);
  81. }
  82. [DebuggerHidden]
  83. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  84. void Run()
  85. {
  86. stateMachine.MoveNext();
  87. }
  88. // dummy interface implementation for TaskTracker.
  89. UniTaskStatus IUniTaskSource.GetStatus(short token)
  90. {
  91. return UniTaskStatus.Pending;
  92. }
  93. UniTaskStatus IUniTaskSource.UnsafeGetStatus()
  94. {
  95. return UniTaskStatus.Pending;
  96. }
  97. void IUniTaskSource.OnCompleted(Action<object> continuation, object state, short token)
  98. {
  99. }
  100. void IUniTaskSource.GetResult(short token)
  101. {
  102. }
  103. }
  104. internal sealed class AsyncUniTask<TStateMachine> : IStateMachineRunnerPromise, IUniTaskSource, ITaskPoolNode<AsyncUniTask<TStateMachine>>
  105. where TStateMachine : IAsyncStateMachine
  106. {
  107. static TaskPool<AsyncUniTask<TStateMachine>> pool;
  108. #if ENABLE_IL2CPP
  109. readonly Action returnDelegate;
  110. #endif
  111. public Action MoveNext { get; }
  112. TStateMachine stateMachine;
  113. UniTaskCompletionSourceCore<AsyncUnit> core;
  114. AsyncUniTask()
  115. {
  116. MoveNext = Run;
  117. #if ENABLE_IL2CPP
  118. returnDelegate = Return;
  119. #endif
  120. }
  121. public static void SetStateMachine(ref TStateMachine stateMachine, ref IStateMachineRunnerPromise runnerPromiseFieldRef)
  122. {
  123. if (!pool.TryPop(out var result))
  124. {
  125. result = new AsyncUniTask<TStateMachine>();
  126. }
  127. TaskTracker.TrackActiveTask(result, 3);
  128. runnerPromiseFieldRef = result; // set runner before copied.
  129. result.stateMachine = stateMachine; // copy struct StateMachine(in release build).
  130. }
  131. AsyncUniTask<TStateMachine> nextNode;
  132. public ref AsyncUniTask<TStateMachine> NextNode => ref nextNode;
  133. static AsyncUniTask()
  134. {
  135. TaskPool.RegisterSizeGetter(typeof(AsyncUniTask<TStateMachine>), () => pool.Size);
  136. }
  137. void Return()
  138. {
  139. TaskTracker.RemoveTracking(this);
  140. core.Reset();
  141. stateMachine = default;
  142. pool.TryPush(this);
  143. }
  144. bool TryReturn()
  145. {
  146. TaskTracker.RemoveTracking(this);
  147. core.Reset();
  148. stateMachine = default;
  149. return pool.TryPush(this);
  150. }
  151. [DebuggerHidden]
  152. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  153. void Run()
  154. {
  155. stateMachine.MoveNext();
  156. }
  157. public UniTask Task
  158. {
  159. [DebuggerHidden]
  160. get
  161. {
  162. return new UniTask(this, core.Version);
  163. }
  164. }
  165. [DebuggerHidden]
  166. public void SetResult()
  167. {
  168. core.TrySetResult(AsyncUnit.Default);
  169. }
  170. [DebuggerHidden]
  171. public void SetException(Exception exception)
  172. {
  173. core.TrySetException(exception);
  174. }
  175. [DebuggerHidden]
  176. public void GetResult(short token)
  177. {
  178. try
  179. {
  180. core.GetResult(token);
  181. }
  182. finally
  183. {
  184. #if ENABLE_IL2CPP
  185. // workaround for IL2CPP bug.
  186. PlayerLoopHelper.AddContinuation(PlayerLoopTiming.LastPostLateUpdate, returnDelegate);
  187. #else
  188. TryReturn();
  189. #endif
  190. }
  191. }
  192. [DebuggerHidden]
  193. public UniTaskStatus GetStatus(short token)
  194. {
  195. return core.GetStatus(token);
  196. }
  197. [DebuggerHidden]
  198. public UniTaskStatus UnsafeGetStatus()
  199. {
  200. return core.UnsafeGetStatus();
  201. }
  202. [DebuggerHidden]
  203. public void OnCompleted(Action<object> continuation, object state, short token)
  204. {
  205. core.OnCompleted(continuation, state, token);
  206. }
  207. }
  208. internal sealed class AsyncUniTask<TStateMachine, T> : IStateMachineRunnerPromise<T>, IUniTaskSource<T>, ITaskPoolNode<AsyncUniTask<TStateMachine, T>>
  209. where TStateMachine : IAsyncStateMachine
  210. {
  211. static TaskPool<AsyncUniTask<TStateMachine, T>> pool;
  212. #if ENABLE_IL2CPP
  213. readonly Action returnDelegate;
  214. #endif
  215. public Action MoveNext { get; }
  216. TStateMachine stateMachine;
  217. UniTaskCompletionSourceCore<T> core;
  218. AsyncUniTask()
  219. {
  220. MoveNext = Run;
  221. #if ENABLE_IL2CPP
  222. returnDelegate = Return;
  223. #endif
  224. }
  225. public static void SetStateMachine(ref TStateMachine stateMachine, ref IStateMachineRunnerPromise<T> runnerPromiseFieldRef)
  226. {
  227. if (!pool.TryPop(out var result))
  228. {
  229. result = new AsyncUniTask<TStateMachine, T>();
  230. }
  231. TaskTracker.TrackActiveTask(result, 3);
  232. runnerPromiseFieldRef = result; // set runner before copied.
  233. result.stateMachine = stateMachine; // copy struct StateMachine(in release build).
  234. }
  235. AsyncUniTask<TStateMachine, T> nextNode;
  236. public ref AsyncUniTask<TStateMachine, T> NextNode => ref nextNode;
  237. static AsyncUniTask()
  238. {
  239. TaskPool.RegisterSizeGetter(typeof(AsyncUniTask<TStateMachine, T>), () => pool.Size);
  240. }
  241. void Return()
  242. {
  243. TaskTracker.RemoveTracking(this);
  244. core.Reset();
  245. stateMachine = default;
  246. pool.TryPush(this);
  247. }
  248. bool TryReturn()
  249. {
  250. TaskTracker.RemoveTracking(this);
  251. core.Reset();
  252. stateMachine = default;
  253. return pool.TryPush(this);
  254. }
  255. [DebuggerHidden]
  256. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  257. void Run()
  258. {
  259. // UnityEngine.Debug.Log($"MoveNext State:" + StateMachineUtility.GetState(stateMachine));
  260. stateMachine.MoveNext();
  261. }
  262. public UniTask<T> Task
  263. {
  264. [DebuggerHidden]
  265. get
  266. {
  267. return new UniTask<T>(this, core.Version);
  268. }
  269. }
  270. [DebuggerHidden]
  271. public void SetResult(T result)
  272. {
  273. core.TrySetResult(result);
  274. }
  275. [DebuggerHidden]
  276. public void SetException(Exception exception)
  277. {
  278. core.TrySetException(exception);
  279. }
  280. [DebuggerHidden]
  281. public T GetResult(short token)
  282. {
  283. try
  284. {
  285. return core.GetResult(token);
  286. }
  287. finally
  288. {
  289. #if ENABLE_IL2CPP
  290. // workaround for IL2CPP bug.
  291. PlayerLoopHelper.AddContinuation(PlayerLoopTiming.LastPostLateUpdate, returnDelegate);
  292. #else
  293. TryReturn();
  294. #endif
  295. }
  296. }
  297. [DebuggerHidden]
  298. void IUniTaskSource.GetResult(short token)
  299. {
  300. GetResult(token);
  301. }
  302. [DebuggerHidden]
  303. public UniTaskStatus GetStatus(short token)
  304. {
  305. return core.GetStatus(token);
  306. }
  307. [DebuggerHidden]
  308. public UniTaskStatus UnsafeGetStatus()
  309. {
  310. return core.UnsafeGetStatus();
  311. }
  312. [DebuggerHidden]
  313. public void OnCompleted(Action<object> continuation, object state, short token)
  314. {
  315. core.OnCompleted(continuation, state, token);
  316. }
  317. }
  318. }