VirtualTimeScheduler.cs 18 KB

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