MainLoopDispatcher.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.CompilerServices;
  5. using System.Threading.Tasks;
  6. namespace Urho
  7. {
  8. internal class MainLoopDispatcher
  9. {
  10. static object staticSyncObj = new object();
  11. static List<Action> actionsToRun;
  12. static HashSet<DelayState> delayTasks;
  13. public static ConfiguredTaskAwaitable<bool> ToMainThreadAsync()
  14. {
  15. var tcs = new TaskCompletionSource<bool>();
  16. InvokeOnMain(() => tcs.TrySetResult(true));
  17. return tcs.Task.ConfigureAwait(false);
  18. }
  19. public static void InvokeOnMain(Action action)
  20. {
  21. if (!Urho.Application.HasCurrent || !Urho.Application.Current.IsActive)
  22. {
  23. throw new InvalidOperationException("InvokeOnMain should be called when Urho.Application is active.");
  24. }
  25. lock (staticSyncObj)
  26. {
  27. if (actionsToRun == null)
  28. actionsToRun = new List<Action>();
  29. actionsToRun.Add(action);
  30. }
  31. }
  32. public static Task<bool> InvokeOnMainAsync(Action action)
  33. {
  34. var tcs = new TaskCompletionSource<bool>();
  35. InvokeOnMain(() =>
  36. {
  37. action?.Invoke();
  38. tcs.TrySetResult(true);
  39. });
  40. return tcs.Task;
  41. }
  42. public static ConfiguredTaskAwaitable<bool> Delay(float seconds)
  43. {
  44. var tcs = new TaskCompletionSource<bool>();
  45. lock (staticSyncObj)
  46. {
  47. if (delayTasks == null)
  48. delayTasks = new HashSet<DelayState>();
  49. delayTasks.Add(new DelayState {Duration = seconds, Task = tcs});
  50. }
  51. return tcs.Task.ConfigureAwait(false);
  52. }
  53. public static ConfiguredTaskAwaitable<bool> Delay(TimeSpan timeSpan) => Delay((float)timeSpan.TotalSeconds);
  54. public static void HandleUpdate(float timeStep)
  55. {
  56. if (actionsToRun != null)
  57. {
  58. Action[] actions;
  59. lock (staticSyncObj)
  60. {
  61. actions = actionsToRun.ToArray();
  62. actionsToRun = null;
  63. }
  64. for (int i = 0; i < actions.Length; i++)
  65. {
  66. actions[i]?.Invoke();
  67. }
  68. }
  69. if (delayTasks != null)
  70. {
  71. DelayState[] delayActions;
  72. lock (staticSyncObj)
  73. {
  74. delayActions = delayTasks.ToArray();
  75. }
  76. for (int i = 0; i < delayActions.Length; i++)
  77. {
  78. var task = delayActions[i];
  79. task.Duration -= timeStep;
  80. if (task.Duration <= 0)
  81. {
  82. task.Task.TrySetResult(true);
  83. lock (staticSyncObj)
  84. delayTasks.Remove(task);
  85. }
  86. }
  87. }
  88. }
  89. class DelayState
  90. {
  91. public float Duration { get; set; }
  92. public TaskCompletionSource<bool> Task { get; set; }
  93. }
  94. }
  95. }