VirtualTimeScheduler.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. namespace System.Reactive.Concurrency
  7. {
  8. /// <summary>
  9. /// Base class for virtual time schedulers.
  10. /// </summary>
  11. /// <typeparam name="TAbsolute">Absolute time representation type.</typeparam>
  12. /// <typeparam name="TRelative">Relative time representation type.</typeparam>
  13. public abstract class VirtualTimeSchedulerBase<TAbsolute, TRelative> : IScheduler, IServiceProvider, IStopwatchProvider
  14. where TAbsolute : IComparable<TAbsolute>
  15. {
  16. /// <summary>
  17. /// Creates a new virtual time scheduler with the default value of TAbsolute as the initial clock value.
  18. /// </summary>
  19. protected VirtualTimeSchedulerBase()
  20. : this(default, Comparer<TAbsolute>.Default)
  21. {
  22. }
  23. /// <summary>
  24. /// Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer.
  25. /// </summary>
  26. /// <param name="initialClock">Initial value for the clock.</param>
  27. /// <param name="comparer">Comparer to determine causality of events based on absolute time.</param>
  28. /// <exception cref="ArgumentNullException"><paramref name="comparer"/> is <c>null</c>.</exception>
  29. protected VirtualTimeSchedulerBase(TAbsolute initialClock, IComparer<TAbsolute> comparer)
  30. {
  31. if (comparer == null)
  32. throw new ArgumentNullException(nameof(comparer));
  33. Clock = initialClock;
  34. Comparer = comparer;
  35. }
  36. /// <summary>
  37. /// Adds a relative time value to an absolute time value.
  38. /// </summary>
  39. /// <param name="absolute">Absolute time value.</param>
  40. /// <param name="relative">Relative time value to add.</param>
  41. /// <returns>The resulting absolute time sum value.</returns>
  42. protected abstract TAbsolute Add(TAbsolute absolute, TRelative relative);
  43. /// <summary>
  44. /// Converts the absolute time value to a DateTimeOffset value.
  45. /// </summary>
  46. /// <param name="absolute">Absolute time value to convert.</param>
  47. /// <returns>The corresponding DateTimeOffset value.</returns>
  48. protected abstract DateTimeOffset ToDateTimeOffset(TAbsolute absolute);
  49. /// <summary>
  50. /// Converts the TimeSpan value to a relative time value.
  51. /// </summary>
  52. /// <param name="timeSpan">TimeSpan value to convert.</param>
  53. /// <returns>The corresponding relative time value.</returns>
  54. protected abstract TRelative ToRelative(TimeSpan timeSpan);
  55. /// <summary>
  56. /// Gets whether the scheduler is enabled to run work.
  57. /// </summary>
  58. public bool IsEnabled { get; private set; }
  59. /// <summary>
  60. /// Gets the comparer used to compare absolute time values.
  61. /// </summary>
  62. protected IComparer<TAbsolute> Comparer { get; }
  63. /// <summary>
  64. /// Schedules an action to be executed at dueTime.
  65. /// </summary>
  66. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  67. /// <param name="state">State passed to the action to be executed.</param>
  68. /// <param name="dueTime">Absolute time at which to execute the action.</param>
  69. /// <param name="action">Action to be executed.</param>
  70. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  71. public abstract IDisposable ScheduleAbsolute<TState>(TState state, TAbsolute dueTime, Func<IScheduler, TState, IDisposable> action);
  72. /// <summary>
  73. /// Schedules an action to be executed at dueTime.
  74. /// </summary>
  75. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  76. /// <param name="state">State passed to the action to be executed.</param>
  77. /// <param name="dueTime">Relative time after which to execute the action.</param>
  78. /// <param name="action">Action to be executed.</param>
  79. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  80. public IDisposable ScheduleRelative<TState>(TState state, TRelative dueTime, Func<IScheduler, TState, IDisposable> action)
  81. {
  82. if (action == null)
  83. throw new ArgumentNullException(nameof(action));
  84. var runAt = Add(Clock, dueTime);
  85. return ScheduleAbsolute(state, runAt, action);
  86. }
  87. /// <summary>
  88. /// Schedules an action to be executed.
  89. /// </summary>
  90. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  91. /// <param name="state">State passed to the action to be executed.</param>
  92. /// <param name="action">Action to be executed.</param>
  93. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  94. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  95. public IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
  96. {
  97. if (action == null)
  98. throw new ArgumentNullException(nameof(action));
  99. return ScheduleAbsolute(state, Clock, action);
  100. }
  101. /// <summary>
  102. /// Schedules an action to be executed after dueTime.
  103. /// </summary>
  104. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  105. /// <param name="state">State passed to the action to be executed.</param>
  106. /// <param name="dueTime">Relative time after which to execute the action.</param>
  107. /// <param name="action">Action to be executed.</param>
  108. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  109. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  110. public IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  111. {
  112. if (action == null)
  113. throw new ArgumentNullException(nameof(action));
  114. return ScheduleRelative(state, ToRelative(dueTime), action);
  115. }
  116. /// <summary>
  117. /// Schedules an action to be executed at dueTime.
  118. /// </summary>
  119. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  120. /// <param name="state">State passed to the action to be executed.</param>
  121. /// <param name="dueTime">Absolute time at which to execute the action.</param>
  122. /// <param name="action">Action to be executed.</param>
  123. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  124. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  125. public IDisposable Schedule<TState>(TState state, DateTimeOffset dueTime, Func<IScheduler, TState, IDisposable> action)
  126. {
  127. if (action == null)
  128. throw new ArgumentNullException(nameof(action));
  129. return ScheduleRelative(state, ToRelative(dueTime - Now), action);
  130. }
  131. /// <summary>
  132. /// Starts the virtual time scheduler.
  133. /// </summary>
  134. public void Start()
  135. {
  136. if (!IsEnabled)
  137. {
  138. IsEnabled = true;
  139. do
  140. {
  141. var next = GetNext();
  142. if (next != null)
  143. {
  144. if (Comparer.Compare(next.DueTime, Clock) > 0)
  145. {
  146. Clock = next.DueTime;
  147. }
  148. next.Invoke();
  149. }
  150. else
  151. {
  152. IsEnabled = false;
  153. }
  154. } while (IsEnabled);
  155. }
  156. }
  157. /// <summary>
  158. /// Stops the virtual time scheduler.
  159. /// </summary>
  160. public void Stop()
  161. {
  162. IsEnabled = false;
  163. }
  164. /// <summary>
  165. /// Advances the scheduler's clock to the specified time, running all work till that point.
  166. /// </summary>
  167. /// <param name="time">Absolute time to advance the scheduler's clock to.</param>
  168. /// <exception cref="ArgumentOutOfRangeException"><paramref name="time"/> is in the past.</exception>
  169. /// <exception cref="InvalidOperationException">The scheduler is already running. VirtualTimeScheduler doesn't support running nested work dispatch loops. To simulate time slippage while running work on the scheduler, use <see cref="Sleep"/>.</exception>
  170. public void AdvanceTo(TAbsolute time)
  171. {
  172. var dueToClock = Comparer.Compare(time, Clock);
  173. if (dueToClock < 0)
  174. throw new ArgumentOutOfRangeException(nameof(time));
  175. if (dueToClock == 0)
  176. return;
  177. if (!IsEnabled)
  178. {
  179. IsEnabled = true;
  180. do
  181. {
  182. var next = GetNext();
  183. if (next != null && Comparer.Compare(next.DueTime, time) <= 0)
  184. {
  185. if (Comparer.Compare(next.DueTime, Clock) > 0)
  186. {
  187. Clock = next.DueTime;
  188. }
  189. next.Invoke();
  190. }
  191. else
  192. {
  193. IsEnabled = false;
  194. }
  195. } while (IsEnabled);
  196. Clock = time;
  197. }
  198. else
  199. {
  200. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings_Linq.CANT_ADVANCE_WHILE_RUNNING, nameof(AdvanceTo)));
  201. }
  202. }
  203. /// <summary>
  204. /// Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan.
  205. /// </summary>
  206. /// <param name="time">Relative time to advance the scheduler's clock by.</param>
  207. /// <exception cref="ArgumentOutOfRangeException"><paramref name="time"/> is negative.</exception>
  208. /// <exception cref="InvalidOperationException">The scheduler is already running. VirtualTimeScheduler doesn't support running nested work dispatch loops. To simulate time slippage while running work on the scheduler, use <see cref="Sleep"/>.</exception>
  209. public void AdvanceBy(TRelative time)
  210. {
  211. var dt = Add(Clock, time);
  212. var dueToClock = Comparer.Compare(dt, Clock);
  213. if (dueToClock < 0)
  214. throw new ArgumentOutOfRangeException(nameof(time));
  215. if (dueToClock == 0)
  216. return;
  217. if (!IsEnabled)
  218. {
  219. AdvanceTo(dt);
  220. }
  221. else
  222. {
  223. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings_Linq.CANT_ADVANCE_WHILE_RUNNING, nameof(AdvanceBy)));
  224. }
  225. }
  226. /// <summary>
  227. /// Advances the scheduler's clock by the specified relative time.
  228. /// </summary>
  229. /// <param name="time">Relative time to advance the scheduler's clock by.</param>
  230. /// <exception cref="ArgumentOutOfRangeException"><paramref name="time"/> is negative.</exception>
  231. public void Sleep(TRelative time)
  232. {
  233. var dt = Add(Clock, time);
  234. var dueToClock = Comparer.Compare(dt, Clock);
  235. if (dueToClock < 0)
  236. throw new ArgumentOutOfRangeException(nameof(time));
  237. Clock = dt;
  238. }
  239. /// <summary>
  240. /// Gets the scheduler's absolute time clock value.
  241. /// </summary>
  242. public TAbsolute Clock
  243. {
  244. get;
  245. protected set;
  246. }
  247. /// <summary>
  248. /// Gets the scheduler's notion of current time.
  249. /// </summary>
  250. public DateTimeOffset Now => ToDateTimeOffset(Clock);
  251. /// <summary>
  252. /// Gets the next scheduled item to be executed.
  253. /// </summary>
  254. /// <returns>The next scheduled item.</returns>
  255. [Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "By design. Side-effecting operation to retrieve the next element.")]
  256. protected abstract IScheduledItem<TAbsolute> GetNext();
  257. object IServiceProvider.GetService(Type serviceType) => GetService(serviceType);
  258. /// <summary>
  259. /// Discovers scheduler services by interface type. The base class implementation supports
  260. /// only the IStopwatchProvider service. To influence service discovery - such as adding
  261. /// support for other scheduler services - derived types can override this method.
  262. /// </summary>
  263. /// <param name="serviceType">Scheduler service interface type to discover.</param>
  264. /// <returns>Object implementing the requested service, if available; null otherwise.</returns>
  265. protected virtual object GetService(Type serviceType)
  266. {
  267. if (serviceType == typeof(IStopwatchProvider))
  268. return this as IStopwatchProvider;
  269. return null;
  270. }
  271. /// <summary>
  272. /// Starts a new stopwatch object.
  273. /// </summary>
  274. /// <returns>New stopwatch object; started at the time of the request.</returns>
  275. public IStopwatch StartStopwatch()
  276. {
  277. var start = ToDateTimeOffset(Clock);
  278. return new VirtualTimeStopwatch(() => ToDateTimeOffset(Clock) - start);
  279. }
  280. private sealed class VirtualTimeStopwatch : IStopwatch
  281. {
  282. private readonly Func<TimeSpan> _getElapsed;
  283. public VirtualTimeStopwatch(Func<TimeSpan> getElapsed)
  284. {
  285. _getElapsed = getElapsed;
  286. }
  287. public TimeSpan Elapsed => _getElapsed();
  288. }
  289. }
  290. /// <summary>
  291. /// Base class for virtual time schedulers using a priority queue for scheduled items.
  292. /// </summary>
  293. /// <typeparam name="TAbsolute">Absolute time representation type.</typeparam>
  294. /// <typeparam name="TRelative">Relative time representation type.</typeparam>
  295. public abstract class VirtualTimeScheduler<TAbsolute, TRelative> : VirtualTimeSchedulerBase<TAbsolute, TRelative>
  296. where TAbsolute : IComparable<TAbsolute>
  297. {
  298. private readonly SchedulerQueue<TAbsolute> queue = new SchedulerQueue<TAbsolute>();
  299. /// <summary>
  300. /// Creates a new virtual time scheduler with the default value of TAbsolute as the initial clock value.
  301. /// </summary>
  302. protected VirtualTimeScheduler()
  303. : base()
  304. {
  305. }
  306. /// <summary>
  307. /// Creates a new virtual time scheduler.
  308. /// </summary>
  309. /// <param name="initialClock">Initial value for the clock.</param>
  310. /// <param name="comparer">Comparer to determine causality of events based on absolute time.</param>
  311. /// <exception cref="ArgumentNullException"><paramref name="comparer"/> is <c>null</c>.</exception>
  312. protected VirtualTimeScheduler(TAbsolute initialClock, IComparer<TAbsolute> comparer)
  313. : base(initialClock, comparer)
  314. {
  315. }
  316. /// <summary>
  317. /// Gets the next scheduled item to be executed.
  318. /// </summary>
  319. /// <returns>The next scheduled item.</returns>
  320. protected override IScheduledItem<TAbsolute> GetNext()
  321. {
  322. lock (queue)
  323. {
  324. while (queue.Count > 0)
  325. {
  326. var next = queue.Peek();
  327. if (next.IsCanceled)
  328. {
  329. queue.Dequeue();
  330. }
  331. else
  332. {
  333. return next;
  334. }
  335. }
  336. }
  337. return null;
  338. }
  339. /// <summary>
  340. /// Schedules an action to be executed at dueTime.
  341. /// </summary>
  342. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  343. /// <param name="state">State passed to the action to be executed.</param>
  344. /// <param name="action">Action to be executed.</param>
  345. /// <param name="dueTime">Absolute time at which to execute the action.</param>
  346. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  347. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  348. public override IDisposable ScheduleAbsolute<TState>(TState state, TAbsolute dueTime, Func<IScheduler, TState, IDisposable> action)
  349. {
  350. if (action == null)
  351. throw new ArgumentNullException(nameof(action));
  352. var si = default(ScheduledItem<TAbsolute, TState>);
  353. var run = new Func<IScheduler, TState, IDisposable>((scheduler, state1) =>
  354. {
  355. lock (queue)
  356. {
  357. queue.Remove(si);
  358. }
  359. return action(scheduler, state1);
  360. });
  361. si = new ScheduledItem<TAbsolute, TState>(this, state, run, dueTime, Comparer);
  362. lock (queue)
  363. {
  364. queue.Enqueue(si);
  365. }
  366. return si;
  367. }
  368. }
  369. }