2
0

MainThreadScheduler.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using System.Threading;
  6. using UnityEngine;
  7. namespace UniRx
  8. {
  9. #if UniRxLibrary
  10. public static partial class SchedulerUnity
  11. {
  12. #else
  13. public static partial class Scheduler
  14. {
  15. public static void SetDefaultForUnity()
  16. {
  17. Scheduler.DefaultSchedulers.ConstantTimeOperations = Scheduler.Immediate;
  18. Scheduler.DefaultSchedulers.TailRecursion = Scheduler.Immediate;
  19. Scheduler.DefaultSchedulers.Iteration = Scheduler.CurrentThread;
  20. Scheduler.DefaultSchedulers.TimeBasedOperations = MainThread;
  21. Scheduler.DefaultSchedulers.AsyncConversions = Scheduler.ThreadPool;
  22. }
  23. #endif
  24. static IScheduler mainThread;
  25. /// <summary>
  26. /// Unity native MainThread Queue Scheduler. Run on mainthread and delayed on coroutine update loop, elapsed time is calculated based on Time.time.
  27. /// </summary>
  28. public static IScheduler MainThread
  29. {
  30. get
  31. {
  32. return mainThread ?? (mainThread = new MainThreadScheduler());
  33. }
  34. }
  35. static IScheduler mainThreadIgnoreTimeScale;
  36. /// <summary>
  37. /// Another MainThread scheduler, delay elapsed time is calculated based on Time.unscaledDeltaTime.
  38. /// </summary>
  39. public static IScheduler MainThreadIgnoreTimeScale
  40. {
  41. get
  42. {
  43. return mainThreadIgnoreTimeScale ?? (mainThreadIgnoreTimeScale = new IgnoreTimeScaleMainThreadScheduler());
  44. }
  45. }
  46. static IScheduler mainThreadFixedUpdate;
  47. /// <summary>
  48. /// Run on fixed update mainthread, delay elapsed time is calculated based on Time.fixedTime.
  49. /// </summary>
  50. public static IScheduler MainThreadFixedUpdate
  51. {
  52. get
  53. {
  54. return mainThreadFixedUpdate ?? (mainThreadFixedUpdate = new FixedUpdateMainThreadScheduler());
  55. }
  56. }
  57. static IScheduler mainThreadEndOfFrame;
  58. /// <summary>
  59. /// Run on end of frame mainthread, delay elapsed time is calculated based on Time.deltaTime.
  60. /// </summary>
  61. public static IScheduler MainThreadEndOfFrame
  62. {
  63. get
  64. {
  65. return mainThreadEndOfFrame ?? (mainThreadEndOfFrame = new EndOfFrameMainThreadScheduler());
  66. }
  67. }
  68. class MainThreadScheduler : IScheduler, ISchedulerPeriodic, ISchedulerQueueing
  69. {
  70. readonly Action<object> scheduleAction;
  71. public MainThreadScheduler()
  72. {
  73. MainThreadDispatcher.Initialize();
  74. scheduleAction = new Action<object>(Schedule);
  75. }
  76. // delay action is run in StartCoroutine
  77. // Okay to action run synchronous and guaranteed run on MainThread
  78. IEnumerator DelayAction(TimeSpan dueTime, Action action, ICancelable cancellation)
  79. {
  80. // zero == every frame
  81. if (dueTime == TimeSpan.Zero)
  82. {
  83. yield return null; // not immediately, run next frame
  84. }
  85. else
  86. {
  87. yield return new WaitForSeconds((float)dueTime.TotalSeconds);
  88. }
  89. if (cancellation.IsDisposed) yield break;
  90. MainThreadDispatcher.UnsafeSend(action);
  91. }
  92. IEnumerator PeriodicAction(TimeSpan period, Action action, ICancelable cancellation)
  93. {
  94. // zero == every frame
  95. if (period == TimeSpan.Zero)
  96. {
  97. while (true)
  98. {
  99. yield return null; // not immediately, run next frame
  100. if (cancellation.IsDisposed) yield break;
  101. MainThreadDispatcher.UnsafeSend(action);
  102. }
  103. }
  104. else
  105. {
  106. var seconds = (float)(period.TotalMilliseconds / 1000.0);
  107. var yieldInstruction = new WaitForSeconds(seconds); // cache single instruction object
  108. while (true)
  109. {
  110. yield return yieldInstruction;
  111. if (cancellation.IsDisposed) yield break;
  112. MainThreadDispatcher.UnsafeSend(action);
  113. }
  114. }
  115. }
  116. public DateTimeOffset Now
  117. {
  118. get { return Scheduler.Now; }
  119. }
  120. void Schedule(object state)
  121. {
  122. var t = (Tuple<BooleanDisposable, Action>)state;
  123. if (!t.Item1.IsDisposed)
  124. {
  125. t.Item2();
  126. }
  127. }
  128. public IDisposable Schedule(Action action)
  129. {
  130. var d = new BooleanDisposable();
  131. MainThreadDispatcher.Post(scheduleAction, Tuple.Create(d, action));
  132. return d;
  133. }
  134. public IDisposable Schedule(DateTimeOffset dueTime, Action action)
  135. {
  136. return Schedule(dueTime - Now, action);
  137. }
  138. public IDisposable Schedule(TimeSpan dueTime, Action action)
  139. {
  140. var d = new BooleanDisposable();
  141. var time = Scheduler.Normalize(dueTime);
  142. MainThreadDispatcher.SendStartCoroutine(DelayAction(time, action, d));
  143. return d;
  144. }
  145. public IDisposable SchedulePeriodic(TimeSpan period, Action action)
  146. {
  147. var d = new BooleanDisposable();
  148. var time = Scheduler.Normalize(period);
  149. MainThreadDispatcher.SendStartCoroutine(PeriodicAction(time, action, d));
  150. return d;
  151. }
  152. void ScheduleQueueing<T>(object state)
  153. {
  154. var t = (Tuple<ICancelable, T, Action<T>>)state;
  155. if (!t.Item1.IsDisposed)
  156. {
  157. t.Item3(t.Item2);
  158. }
  159. }
  160. public void ScheduleQueueing<T>(ICancelable cancel, T state, Action<T> action)
  161. {
  162. MainThreadDispatcher.Post(QueuedAction<T>.Instance, Tuple.Create(cancel, state, action));
  163. }
  164. static class QueuedAction<T>
  165. {
  166. public static readonly Action<object> Instance = new Action<object>(Invoke);
  167. public static void Invoke(object state)
  168. {
  169. var t = (Tuple<ICancelable, T, Action<T>>)state;
  170. if (!t.Item1.IsDisposed)
  171. {
  172. t.Item3(t.Item2);
  173. }
  174. }
  175. }
  176. }
  177. class IgnoreTimeScaleMainThreadScheduler : IScheduler, ISchedulerPeriodic, ISchedulerQueueing
  178. {
  179. readonly Action<object> scheduleAction;
  180. public IgnoreTimeScaleMainThreadScheduler()
  181. {
  182. MainThreadDispatcher.Initialize();
  183. scheduleAction = new Action<object>(Schedule);
  184. }
  185. IEnumerator DelayAction(TimeSpan dueTime, Action action, ICancelable cancellation)
  186. {
  187. if (dueTime == TimeSpan.Zero)
  188. {
  189. yield return null;
  190. if (cancellation.IsDisposed) yield break;
  191. MainThreadDispatcher.UnsafeSend(action);
  192. }
  193. else
  194. {
  195. var elapsed = 0f;
  196. var dt = (float)dueTime.TotalSeconds;
  197. while (true)
  198. {
  199. yield return null;
  200. if (cancellation.IsDisposed) break;
  201. elapsed += Time.unscaledDeltaTime;
  202. if (elapsed >= dt)
  203. {
  204. MainThreadDispatcher.UnsafeSend(action);
  205. break;
  206. }
  207. }
  208. }
  209. }
  210. IEnumerator PeriodicAction(TimeSpan period, Action action, ICancelable cancellation)
  211. {
  212. // zero == every frame
  213. if (period == TimeSpan.Zero)
  214. {
  215. while (true)
  216. {
  217. yield return null; // not immediately, run next frame
  218. if (cancellation.IsDisposed) yield break;
  219. MainThreadDispatcher.UnsafeSend(action);
  220. }
  221. }
  222. else
  223. {
  224. var elapsed = 0f;
  225. var dt = (float)period.TotalSeconds;
  226. while (true)
  227. {
  228. yield return null;
  229. if (cancellation.IsDisposed) break;
  230. elapsed += Time.unscaledDeltaTime;
  231. if (elapsed >= dt)
  232. {
  233. MainThreadDispatcher.UnsafeSend(action);
  234. elapsed = 0;
  235. }
  236. }
  237. }
  238. }
  239. public DateTimeOffset Now
  240. {
  241. get { return Scheduler.Now; }
  242. }
  243. void Schedule(object state)
  244. {
  245. var t = (Tuple<BooleanDisposable, Action>)state;
  246. if (!t.Item1.IsDisposed)
  247. {
  248. t.Item2();
  249. }
  250. }
  251. public IDisposable Schedule(Action action)
  252. {
  253. var d = new BooleanDisposable();
  254. MainThreadDispatcher.Post(scheduleAction, Tuple.Create(d, action));
  255. return d;
  256. }
  257. public IDisposable Schedule(DateTimeOffset dueTime, Action action)
  258. {
  259. return Schedule(dueTime - Now, action);
  260. }
  261. public IDisposable Schedule(TimeSpan dueTime, Action action)
  262. {
  263. var d = new BooleanDisposable();
  264. var time = Scheduler.Normalize(dueTime);
  265. MainThreadDispatcher.SendStartCoroutine(DelayAction(time, action, d));
  266. return d;
  267. }
  268. public IDisposable SchedulePeriodic(TimeSpan period, Action action)
  269. {
  270. var d = new BooleanDisposable();
  271. var time = Scheduler.Normalize(period);
  272. MainThreadDispatcher.SendStartCoroutine(PeriodicAction(time, action, d));
  273. return d;
  274. }
  275. public void ScheduleQueueing<T>(ICancelable cancel, T state, Action<T> action)
  276. {
  277. MainThreadDispatcher.Post(QueuedAction<T>.Instance, Tuple.Create(cancel, state, action));
  278. }
  279. static class QueuedAction<T>
  280. {
  281. public static readonly Action<object> Instance = new Action<object>(Invoke);
  282. public static void Invoke(object state)
  283. {
  284. var t = (Tuple<ICancelable, T, Action<T>>)state;
  285. if (!t.Item1.IsDisposed)
  286. {
  287. t.Item3(t.Item2);
  288. }
  289. }
  290. }
  291. }
  292. class FixedUpdateMainThreadScheduler : IScheduler, ISchedulerPeriodic, ISchedulerQueueing
  293. {
  294. public FixedUpdateMainThreadScheduler()
  295. {
  296. MainThreadDispatcher.Initialize();
  297. }
  298. IEnumerator ImmediateAction<T>(T state, Action<T> action, ICancelable cancellation)
  299. {
  300. yield return null;
  301. if (cancellation.IsDisposed) yield break;
  302. MainThreadDispatcher.UnsafeSend(action, state);
  303. }
  304. IEnumerator DelayAction(TimeSpan dueTime, Action action, ICancelable cancellation)
  305. {
  306. if (dueTime == TimeSpan.Zero)
  307. {
  308. yield return null;
  309. if (cancellation.IsDisposed) yield break;
  310. MainThreadDispatcher.UnsafeSend(action);
  311. }
  312. else
  313. {
  314. var startTime = Time.fixedTime;
  315. var dt = (float)dueTime.TotalSeconds;
  316. while (true)
  317. {
  318. yield return null;
  319. if (cancellation.IsDisposed) break;
  320. var elapsed = Time.fixedTime - startTime;
  321. if (elapsed >= dt)
  322. {
  323. MainThreadDispatcher.UnsafeSend(action);
  324. break;
  325. }
  326. }
  327. }
  328. }
  329. IEnumerator PeriodicAction(TimeSpan period, Action action, ICancelable cancellation)
  330. {
  331. // zero == every frame
  332. if (period == TimeSpan.Zero)
  333. {
  334. while (true)
  335. {
  336. yield return null;
  337. if (cancellation.IsDisposed) yield break;
  338. MainThreadDispatcher.UnsafeSend(action);
  339. }
  340. }
  341. else
  342. {
  343. var startTime = Time.fixedTime;
  344. var dt = (float)period.TotalSeconds;
  345. while (true)
  346. {
  347. yield return null;
  348. if (cancellation.IsDisposed) break;
  349. var ft = Time.fixedTime;
  350. var elapsed = ft - startTime;
  351. if (elapsed >= dt)
  352. {
  353. MainThreadDispatcher.UnsafeSend(action);
  354. startTime = ft;
  355. }
  356. }
  357. }
  358. }
  359. public DateTimeOffset Now
  360. {
  361. get { return Scheduler.Now; }
  362. }
  363. public IDisposable Schedule(Action action)
  364. {
  365. return Schedule(TimeSpan.Zero, action);
  366. }
  367. public IDisposable Schedule(DateTimeOffset dueTime, Action action)
  368. {
  369. return Schedule(dueTime - Now, action);
  370. }
  371. public IDisposable Schedule(TimeSpan dueTime, Action action)
  372. {
  373. var d = new BooleanDisposable();
  374. var time = Scheduler.Normalize(dueTime);
  375. MainThreadDispatcher.StartFixedUpdateMicroCoroutine(DelayAction(time, action, d));
  376. return d;
  377. }
  378. public IDisposable SchedulePeriodic(TimeSpan period, Action action)
  379. {
  380. var d = new BooleanDisposable();
  381. var time = Scheduler.Normalize(period);
  382. MainThreadDispatcher.StartFixedUpdateMicroCoroutine(PeriodicAction(time, action, d));
  383. return d;
  384. }
  385. public void ScheduleQueueing<T>(ICancelable cancel, T state, Action<T> action)
  386. {
  387. MainThreadDispatcher.StartFixedUpdateMicroCoroutine(ImmediateAction(state, action, cancel));
  388. }
  389. }
  390. class EndOfFrameMainThreadScheduler : IScheduler, ISchedulerPeriodic, ISchedulerQueueing
  391. {
  392. public EndOfFrameMainThreadScheduler()
  393. {
  394. MainThreadDispatcher.Initialize();
  395. }
  396. IEnumerator ImmediateAction<T>(T state, Action<T> action, ICancelable cancellation)
  397. {
  398. yield return null;
  399. if (cancellation.IsDisposed) yield break;
  400. MainThreadDispatcher.UnsafeSend(action, state);
  401. }
  402. IEnumerator DelayAction(TimeSpan dueTime, Action action, ICancelable cancellation)
  403. {
  404. if (dueTime == TimeSpan.Zero)
  405. {
  406. yield return null;
  407. if (cancellation.IsDisposed) yield break;
  408. MainThreadDispatcher.UnsafeSend(action);
  409. }
  410. else
  411. {
  412. var elapsed = 0f;
  413. var dt = (float)dueTime.TotalSeconds;
  414. while (true)
  415. {
  416. yield return null;
  417. if (cancellation.IsDisposed) break;
  418. elapsed += Time.deltaTime;
  419. if (elapsed >= dt)
  420. {
  421. MainThreadDispatcher.UnsafeSend(action);
  422. break;
  423. }
  424. }
  425. }
  426. }
  427. IEnumerator PeriodicAction(TimeSpan period, Action action, ICancelable cancellation)
  428. {
  429. // zero == every frame
  430. if (period == TimeSpan.Zero)
  431. {
  432. while (true)
  433. {
  434. yield return null;
  435. if (cancellation.IsDisposed) yield break;
  436. MainThreadDispatcher.UnsafeSend(action);
  437. }
  438. }
  439. else
  440. {
  441. var elapsed = 0f;
  442. var dt = (float)period.TotalSeconds;
  443. while (true)
  444. {
  445. yield return null;
  446. if (cancellation.IsDisposed) break;
  447. elapsed += Time.deltaTime;
  448. if (elapsed >= dt)
  449. {
  450. MainThreadDispatcher.UnsafeSend(action);
  451. elapsed = 0;
  452. }
  453. }
  454. }
  455. }
  456. public DateTimeOffset Now
  457. {
  458. get { return Scheduler.Now; }
  459. }
  460. public IDisposable Schedule(Action action)
  461. {
  462. return Schedule(TimeSpan.Zero, action);
  463. }
  464. public IDisposable Schedule(DateTimeOffset dueTime, Action action)
  465. {
  466. return Schedule(dueTime - Now, action);
  467. }
  468. public IDisposable Schedule(TimeSpan dueTime, Action action)
  469. {
  470. var d = new BooleanDisposable();
  471. var time = Scheduler.Normalize(dueTime);
  472. MainThreadDispatcher.StartEndOfFrameMicroCoroutine(DelayAction(time, action, d));
  473. return d;
  474. }
  475. public IDisposable SchedulePeriodic(TimeSpan period, Action action)
  476. {
  477. var d = new BooleanDisposable();
  478. var time = Scheduler.Normalize(period);
  479. MainThreadDispatcher.StartEndOfFrameMicroCoroutine(PeriodicAction(time, action, d));
  480. return d;
  481. }
  482. public void ScheduleQueueing<T>(ICancelable cancel, T state, Action<T> action)
  483. {
  484. MainThreadDispatcher.StartEndOfFrameMicroCoroutine(ImmediateAction(state, action, cancel));
  485. }
  486. }
  487. }
  488. }