UniTask.Threading.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
  2. using System;
  3. using System.Runtime.CompilerServices;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using Cysharp.Threading.Tasks.Internal;
  7. namespace Cysharp.Threading.Tasks
  8. {
  9. public partial struct UniTask
  10. {
  11. #if UNITY_2018_3_OR_NEWER
  12. /// <summary>
  13. /// If running on mainthread, do nothing. Otherwise, same as UniTask.Yield(PlayerLoopTiming.Update).
  14. /// </summary>
  15. public static SwitchToMainThreadAwaitable SwitchToMainThread(CancellationToken cancellationToken = default)
  16. {
  17. return new SwitchToMainThreadAwaitable(PlayerLoopTiming.Update, cancellationToken);
  18. }
  19. /// <summary>
  20. /// If running on mainthread, do nothing. Otherwise, same as UniTask.Yield(timing).
  21. /// </summary>
  22. public static SwitchToMainThreadAwaitable SwitchToMainThread(PlayerLoopTiming timing, CancellationToken cancellationToken = default)
  23. {
  24. return new SwitchToMainThreadAwaitable(timing, cancellationToken);
  25. }
  26. /// <summary>
  27. /// Return to mainthread(same as await SwitchToMainThread) after using scope is closed.
  28. /// </summary>
  29. public static ReturnToMainThread ReturnToMainThread(CancellationToken cancellationToken = default)
  30. {
  31. return new ReturnToMainThread(PlayerLoopTiming.Update, cancellationToken);
  32. }
  33. /// <summary>
  34. /// Return to mainthread(same as await SwitchToMainThread) after using scope is closed.
  35. /// </summary>
  36. public static ReturnToMainThread ReturnToMainThread(PlayerLoopTiming timing, CancellationToken cancellationToken = default)
  37. {
  38. return new ReturnToMainThread(timing, cancellationToken);
  39. }
  40. /// <summary>
  41. /// Queue the action to PlayerLoop.
  42. /// </summary>
  43. public static void Post(Action action, PlayerLoopTiming timing = PlayerLoopTiming.Update)
  44. {
  45. PlayerLoopHelper.AddContinuation(timing, action);
  46. }
  47. #endif
  48. public static SwitchToThreadPoolAwaitable SwitchToThreadPool()
  49. {
  50. return new SwitchToThreadPoolAwaitable();
  51. }
  52. /// <summary>
  53. /// Note: use SwitchToThreadPool is recommended.
  54. /// </summary>
  55. public static SwitchToTaskPoolAwaitable SwitchToTaskPool()
  56. {
  57. return new SwitchToTaskPoolAwaitable();
  58. }
  59. public static SwitchToSynchronizationContextAwaitable SwitchToSynchronizationContext(SynchronizationContext synchronizationContext, CancellationToken cancellationToken = default)
  60. {
  61. Error.ThrowArgumentNullException(synchronizationContext, nameof(synchronizationContext));
  62. return new SwitchToSynchronizationContextAwaitable(synchronizationContext, cancellationToken);
  63. }
  64. public static ReturnToSynchronizationContext ReturnToSynchronizationContext(SynchronizationContext synchronizationContext, CancellationToken cancellationToken = default)
  65. {
  66. return new ReturnToSynchronizationContext(synchronizationContext, false, cancellationToken);
  67. }
  68. public static ReturnToSynchronizationContext ReturnToCurrentSynchronizationContext(bool dontPostWhenSameContext = true, CancellationToken cancellationToken = default)
  69. {
  70. return new ReturnToSynchronizationContext(SynchronizationContext.Current, dontPostWhenSameContext, cancellationToken);
  71. }
  72. }
  73. #if UNITY_2018_3_OR_NEWER
  74. public struct SwitchToMainThreadAwaitable
  75. {
  76. readonly PlayerLoopTiming playerLoopTiming;
  77. readonly CancellationToken cancellationToken;
  78. public SwitchToMainThreadAwaitable(PlayerLoopTiming playerLoopTiming, CancellationToken cancellationToken)
  79. {
  80. this.playerLoopTiming = playerLoopTiming;
  81. this.cancellationToken = cancellationToken;
  82. }
  83. public Awaiter GetAwaiter() => new Awaiter(playerLoopTiming, cancellationToken);
  84. public struct Awaiter : ICriticalNotifyCompletion
  85. {
  86. readonly PlayerLoopTiming playerLoopTiming;
  87. readonly CancellationToken cancellationToken;
  88. public Awaiter(PlayerLoopTiming playerLoopTiming, CancellationToken cancellationToken)
  89. {
  90. this.playerLoopTiming = playerLoopTiming;
  91. this.cancellationToken = cancellationToken;
  92. }
  93. public bool IsCompleted
  94. {
  95. get
  96. {
  97. var currentThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId;
  98. if (PlayerLoopHelper.MainThreadId == currentThreadId)
  99. {
  100. return true; // run immediate.
  101. }
  102. else
  103. {
  104. return false; // register continuation.
  105. }
  106. }
  107. }
  108. public void GetResult() { cancellationToken.ThrowIfCancellationRequested(); }
  109. public void OnCompleted(Action continuation)
  110. {
  111. PlayerLoopHelper.AddContinuation(playerLoopTiming, continuation);
  112. }
  113. public void UnsafeOnCompleted(Action continuation)
  114. {
  115. PlayerLoopHelper.AddContinuation(playerLoopTiming, continuation);
  116. }
  117. }
  118. }
  119. public struct ReturnToMainThread
  120. {
  121. readonly PlayerLoopTiming playerLoopTiming;
  122. readonly CancellationToken cancellationToken;
  123. public ReturnToMainThread(PlayerLoopTiming playerLoopTiming, CancellationToken cancellationToken)
  124. {
  125. this.playerLoopTiming = playerLoopTiming;
  126. this.cancellationToken = cancellationToken;
  127. }
  128. public Awaiter DisposeAsync()
  129. {
  130. return new Awaiter(playerLoopTiming, cancellationToken); // run immediate.
  131. }
  132. public readonly struct Awaiter : ICriticalNotifyCompletion
  133. {
  134. readonly PlayerLoopTiming timing;
  135. readonly CancellationToken cancellationToken;
  136. public Awaiter(PlayerLoopTiming timing, CancellationToken cancellationToken)
  137. {
  138. this.timing = timing;
  139. this.cancellationToken = cancellationToken;
  140. }
  141. public Awaiter GetAwaiter() => this;
  142. public bool IsCompleted => PlayerLoopHelper.MainThreadId == System.Threading.Thread.CurrentThread.ManagedThreadId;
  143. public void GetResult() { cancellationToken.ThrowIfCancellationRequested(); }
  144. public void OnCompleted(Action continuation)
  145. {
  146. PlayerLoopHelper.AddContinuation(timing, continuation);
  147. }
  148. public void UnsafeOnCompleted(Action continuation)
  149. {
  150. PlayerLoopHelper.AddContinuation(timing, continuation);
  151. }
  152. }
  153. }
  154. #endif
  155. public struct SwitchToThreadPoolAwaitable
  156. {
  157. public Awaiter GetAwaiter() => new Awaiter();
  158. public struct Awaiter : ICriticalNotifyCompletion
  159. {
  160. static readonly WaitCallback switchToCallback = Callback;
  161. public bool IsCompleted => false;
  162. public void GetResult() { }
  163. public void OnCompleted(Action continuation)
  164. {
  165. ThreadPool.QueueUserWorkItem(switchToCallback, continuation);
  166. }
  167. public void UnsafeOnCompleted(Action continuation)
  168. {
  169. #if NETCOREAPP3_1
  170. ThreadPool.UnsafeQueueUserWorkItem(ThreadPoolWorkItem.Create(continuation), false);
  171. #else
  172. ThreadPool.UnsafeQueueUserWorkItem(switchToCallback, continuation);
  173. #endif
  174. }
  175. static void Callback(object state)
  176. {
  177. var continuation = (Action)state;
  178. continuation();
  179. }
  180. }
  181. #if NETCOREAPP3_1
  182. sealed class ThreadPoolWorkItem : IThreadPoolWorkItem, ITaskPoolNode<ThreadPoolWorkItem>
  183. {
  184. static TaskPool<ThreadPoolWorkItem> pool;
  185. ThreadPoolWorkItem nextNode;
  186. public ref ThreadPoolWorkItem NextNode => ref nextNode;
  187. static ThreadPoolWorkItem()
  188. {
  189. TaskPool.RegisterSizeGetter(typeof(ThreadPoolWorkItem), () => pool.Size);
  190. }
  191. Action continuation;
  192. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  193. public static ThreadPoolWorkItem Create(Action continuation)
  194. {
  195. if (!pool.TryPop(out var item))
  196. {
  197. item = new ThreadPoolWorkItem();
  198. }
  199. item.continuation = continuation;
  200. return item;
  201. }
  202. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  203. public void Execute()
  204. {
  205. var call = continuation;
  206. continuation = null;
  207. if (call != null)
  208. {
  209. pool.TryPush(this);
  210. call.Invoke();
  211. }
  212. }
  213. }
  214. #endif
  215. }
  216. public struct SwitchToTaskPoolAwaitable
  217. {
  218. public Awaiter GetAwaiter() => new Awaiter();
  219. public struct Awaiter : ICriticalNotifyCompletion
  220. {
  221. static readonly Action<object> switchToCallback = Callback;
  222. public bool IsCompleted => false;
  223. public void GetResult() { }
  224. public void OnCompleted(Action continuation)
  225. {
  226. Task.Factory.StartNew(switchToCallback, continuation, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  227. }
  228. public void UnsafeOnCompleted(Action continuation)
  229. {
  230. Task.Factory.StartNew(switchToCallback, continuation, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  231. }
  232. static void Callback(object state)
  233. {
  234. var continuation = (Action)state;
  235. continuation();
  236. }
  237. }
  238. }
  239. public struct SwitchToSynchronizationContextAwaitable
  240. {
  241. readonly SynchronizationContext synchronizationContext;
  242. readonly CancellationToken cancellationToken;
  243. public SwitchToSynchronizationContextAwaitable(SynchronizationContext synchronizationContext, CancellationToken cancellationToken)
  244. {
  245. this.synchronizationContext = synchronizationContext;
  246. this.cancellationToken = cancellationToken;
  247. }
  248. public Awaiter GetAwaiter() => new Awaiter(synchronizationContext, cancellationToken);
  249. public struct Awaiter : ICriticalNotifyCompletion
  250. {
  251. static readonly SendOrPostCallback switchToCallback = Callback;
  252. readonly SynchronizationContext synchronizationContext;
  253. readonly CancellationToken cancellationToken;
  254. public Awaiter(SynchronizationContext synchronizationContext, CancellationToken cancellationToken)
  255. {
  256. this.synchronizationContext = synchronizationContext;
  257. this.cancellationToken = cancellationToken;
  258. }
  259. public bool IsCompleted => false;
  260. public void GetResult() { cancellationToken.ThrowIfCancellationRequested(); }
  261. public void OnCompleted(Action continuation)
  262. {
  263. synchronizationContext.Post(switchToCallback, continuation);
  264. }
  265. public void UnsafeOnCompleted(Action continuation)
  266. {
  267. synchronizationContext.Post(switchToCallback, continuation);
  268. }
  269. static void Callback(object state)
  270. {
  271. var continuation = (Action)state;
  272. continuation();
  273. }
  274. }
  275. }
  276. public struct ReturnToSynchronizationContext
  277. {
  278. readonly SynchronizationContext syncContext;
  279. readonly bool dontPostWhenSameContext;
  280. readonly CancellationToken cancellationToken;
  281. public ReturnToSynchronizationContext(SynchronizationContext syncContext, bool dontPostWhenSameContext, CancellationToken cancellationToken)
  282. {
  283. this.syncContext = syncContext;
  284. this.dontPostWhenSameContext = dontPostWhenSameContext;
  285. this.cancellationToken = cancellationToken;
  286. }
  287. public Awaiter DisposeAsync()
  288. {
  289. return new Awaiter(syncContext, dontPostWhenSameContext, cancellationToken);
  290. }
  291. public struct Awaiter : ICriticalNotifyCompletion
  292. {
  293. static readonly SendOrPostCallback switchToCallback = Callback;
  294. readonly SynchronizationContext synchronizationContext;
  295. readonly bool dontPostWhenSameContext;
  296. readonly CancellationToken cancellationToken;
  297. public Awaiter(SynchronizationContext synchronizationContext, bool dontPostWhenSameContext, CancellationToken cancellationToken)
  298. {
  299. this.synchronizationContext = synchronizationContext;
  300. this.dontPostWhenSameContext = dontPostWhenSameContext;
  301. this.cancellationToken = cancellationToken;
  302. }
  303. public Awaiter GetAwaiter() => this;
  304. public bool IsCompleted
  305. {
  306. get
  307. {
  308. if (!dontPostWhenSameContext) return false;
  309. var current = SynchronizationContext.Current;
  310. if (current == synchronizationContext)
  311. {
  312. return true;
  313. }
  314. else
  315. {
  316. return false;
  317. }
  318. }
  319. }
  320. public void GetResult() { cancellationToken.ThrowIfCancellationRequested(); }
  321. public void OnCompleted(Action continuation)
  322. {
  323. synchronizationContext.Post(switchToCallback, continuation);
  324. }
  325. public void UnsafeOnCompleted(Action continuation)
  326. {
  327. synchronizationContext.Post(switchToCallback, continuation);
  328. }
  329. static void Callback(object state)
  330. {
  331. var continuation = (Action)state;
  332. continuation();
  333. }
  334. }
  335. }
  336. }