TimedEvents.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. #nullable enable
  2. using System.Collections.ObjectModel;
  3. namespace Terminal.Gui;
  4. /// <summary>
  5. /// Handles timeouts and idles
  6. /// </summary>
  7. public class TimedEvents : ITimedEvents
  8. {
  9. internal List<Func<bool>> _idleHandlers = new ();
  10. internal SortedList<long, Timeout> _timeouts = new ();
  11. /// <summary>The idle handlers and lock that must be held while manipulating them</summary>
  12. private readonly object _idleHandlersLock = new ();
  13. private readonly object _timeoutsLockToken = new ();
  14. /// <summary>Gets a copy of the list of all idle handlers.</summary>
  15. public ReadOnlyCollection<Func<bool>> IdleHandlers
  16. {
  17. get
  18. {
  19. lock (_idleHandlersLock)
  20. {
  21. return new List<Func<bool>> (_idleHandlers).AsReadOnly ();
  22. }
  23. }
  24. }
  25. /// <summary>
  26. /// Gets the list of all timeouts sorted by the <see cref="TimeSpan"/> time ticks. A shorter limit time can be
  27. /// added at the end, but it will be called before an earlier addition that has a longer limit time.
  28. /// </summary>
  29. public SortedList<long, Timeout> Timeouts => _timeouts;
  30. /// <inheritdoc />
  31. public void AddIdle (Func<bool> idleHandler)
  32. {
  33. lock (_idleHandlersLock)
  34. {
  35. _idleHandlers.Add (idleHandler);
  36. }
  37. }
  38. /// <inheritdoc/>
  39. public event EventHandler<TimeoutEventArgs>? TimeoutAdded;
  40. private void AddTimeout (TimeSpan time, Timeout timeout)
  41. {
  42. lock (_timeoutsLockToken)
  43. {
  44. long k = (DateTime.UtcNow + time).Ticks;
  45. _timeouts.Add (NudgeToUniqueKey (k), timeout);
  46. TimeoutAdded?.Invoke (this, new TimeoutEventArgs (timeout, k));
  47. }
  48. }
  49. /// <summary>
  50. /// Finds the closest number to <paramref name="k"/> that is not present in <see cref="_timeouts"/>
  51. /// (incrementally).
  52. /// </summary>
  53. /// <param name="k"></param>
  54. /// <returns></returns>
  55. private long NudgeToUniqueKey (long k)
  56. {
  57. lock (_timeoutsLockToken)
  58. {
  59. while (_timeouts.ContainsKey (k))
  60. {
  61. k++;
  62. }
  63. }
  64. return k;
  65. }
  66. // PERF: This is heavier than it looks.
  67. // CONCURRENCY: Potential deadlock city here.
  68. // CONCURRENCY: Multiple concurrency pitfalls on the delegates themselves.
  69. // INTENT: It looks like the general architecture here is trying to be a form of publisher/consumer pattern.
  70. private void RunIdle ()
  71. {
  72. Func<bool> [] iterate;
  73. lock (_idleHandlersLock)
  74. {
  75. iterate = _idleHandlers.ToArray ();
  76. _idleHandlers = new List<Func<bool>> ();
  77. }
  78. foreach (Func<bool> idle in iterate)
  79. {
  80. if (idle ())
  81. {
  82. lock (_idleHandlersLock)
  83. {
  84. _idleHandlers.Add (idle);
  85. }
  86. }
  87. }
  88. }
  89. /// <inheritdoc/>
  90. public void LockAndRunTimers ()
  91. {
  92. lock (_timeoutsLockToken)
  93. {
  94. if (_timeouts.Count > 0)
  95. {
  96. RunTimers ();
  97. }
  98. }
  99. }
  100. /// <inheritdoc/>
  101. public void LockAndRunIdles ()
  102. {
  103. bool runIdle;
  104. lock (_idleHandlersLock)
  105. {
  106. runIdle = _idleHandlers.Count > 0;
  107. }
  108. if (runIdle)
  109. {
  110. RunIdle ();
  111. }
  112. }
  113. private void RunTimers ()
  114. {
  115. long now = DateTime.UtcNow.Ticks;
  116. SortedList<long, Timeout> copy;
  117. // lock prevents new timeouts being added
  118. // after we have taken the copy but before
  119. // we have allocated a new list (which would
  120. // result in lost timeouts or errors during enumeration)
  121. lock (_timeoutsLockToken)
  122. {
  123. copy = _timeouts;
  124. _timeouts = new SortedList<long, Timeout> ();
  125. }
  126. foreach ((long k, Timeout timeout) in copy)
  127. {
  128. if (k < now)
  129. {
  130. if (timeout.Callback ())
  131. {
  132. AddTimeout (timeout.Span, timeout);
  133. }
  134. }
  135. else
  136. {
  137. lock (_timeoutsLockToken)
  138. {
  139. _timeouts.Add (NudgeToUniqueKey (k), timeout);
  140. }
  141. }
  142. }
  143. }
  144. /// <inheritdoc/>
  145. public bool RemoveIdle (Func<bool> token)
  146. {
  147. lock (_idleHandlersLock)
  148. {
  149. return _idleHandlers.Remove (token);
  150. }
  151. }
  152. /// <summary>Removes a previously scheduled timeout</summary>
  153. /// <remarks>The token parameter is the value returned by AddTimeout.</remarks>
  154. /// Returns
  155. /// <see langword="true"/>
  156. /// if the timeout is successfully removed; otherwise,
  157. /// <see langword="false"/>
  158. /// .
  159. /// This method also returns
  160. /// <see langword="false"/>
  161. /// if the timeout is not found.
  162. public bool RemoveTimeout (object token)
  163. {
  164. lock (_timeoutsLockToken)
  165. {
  166. int idx = _timeouts.IndexOfValue ((token as Timeout)!);
  167. if (idx == -1)
  168. {
  169. return false;
  170. }
  171. _timeouts.RemoveAt (idx);
  172. }
  173. return true;
  174. }
  175. /// <summary>Adds a timeout to the <see cref="MainLoop"/>.</summary>
  176. /// <remarks>
  177. /// When time specified passes, the callback will be invoked. If the callback returns true, the timeout will be
  178. /// reset, repeating the invocation. If it returns false, the timeout will stop and be removed. The returned value is a
  179. /// token that can be used to stop the timeout by calling <see cref="RemoveTimeout(object)"/>.
  180. /// </remarks>
  181. public object AddTimeout (TimeSpan time, Func<bool> callback)
  182. {
  183. ArgumentNullException.ThrowIfNull (callback);
  184. var timeout = new Timeout { Span = time, Callback = callback };
  185. AddTimeout (time, timeout);
  186. return timeout;
  187. }
  188. /// <inheritdoc/>
  189. public bool CheckTimersAndIdleHandlers (out int waitTimeout)
  190. {
  191. long now = DateTime.UtcNow.Ticks;
  192. waitTimeout = 0;
  193. lock (_timeoutsLockToken)
  194. {
  195. if (_timeouts.Count > 0)
  196. {
  197. waitTimeout = (int)((_timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  198. if (waitTimeout < 0)
  199. {
  200. // This avoids 'poll' waiting infinitely if 'waitTimeout < 0' until some action is detected
  201. // This can occur after IMainLoopDriver.Wakeup is executed where the pollTimeout is less than 0
  202. // and no event occurred in elapsed time when the 'poll' is start running again.
  203. waitTimeout = 0;
  204. }
  205. return true;
  206. }
  207. // ManualResetEventSlim.Wait, which is called by IMainLoopDriver.EventsPending, will wait indefinitely if
  208. // the timeout is -1.
  209. waitTimeout = -1;
  210. }
  211. // There are no timers set, check if there are any idle handlers
  212. lock (_idleHandlersLock)
  213. {
  214. return _idleHandlers.Count > 0;
  215. }
  216. }
  217. }