VirtualTimeScheduler.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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 null.</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
  60. {
  61. get;
  62. private set;
  63. }
  64. /// <summary>
  65. /// Gets the comparer used to compare absolute time values.
  66. /// </summary>
  67. protected IComparer<TAbsolute> Comparer
  68. {
  69. get;
  70. private set;
  71. }
  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">Absolute time at 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 abstract IDisposable ScheduleAbsolute<TState>(TState state, TAbsolute dueTime, Func<IScheduler, TState, IDisposable> action);
  81. /// <summary>
  82. /// Schedules an action to be executed at dueTime.
  83. /// </summary>
  84. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  85. /// <param name="state">State passed to the action to be executed.</param>
  86. /// <param name="dueTime">Relative time after which to execute the action.</param>
  87. /// <param name="action">Action to be executed.</param>
  88. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  89. public IDisposable ScheduleRelative<TState>(TState state, TRelative dueTime, Func<IScheduler, TState, IDisposable> action)
  90. {
  91. if (action == null)
  92. throw new ArgumentNullException(nameof(action));
  93. var runAt = Add(Clock, dueTime);
  94. return ScheduleAbsolute(state, runAt, action);
  95. }
  96. /// <summary>
  97. /// Schedules an action to be executed.
  98. /// </summary>
  99. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  100. /// <param name="state">State passed to the action to be executed.</param>
  101. /// <param name="action">Action to be executed.</param>
  102. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  103. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  104. public IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
  105. {
  106. if (action == null)
  107. throw new ArgumentNullException(nameof(action));
  108. return ScheduleAbsolute(state, Clock, action);
  109. }
  110. /// <summary>
  111. /// Schedules an action to be executed after dueTime.
  112. /// </summary>
  113. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  114. /// <param name="state">State passed to the action to be executed.</param>
  115. /// <param name="dueTime">Relative time after which to execute the action.</param>
  116. /// <param name="action">Action to be executed.</param>
  117. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  118. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  119. public IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  120. {
  121. if (action == null)
  122. throw new ArgumentNullException(nameof(action));
  123. return ScheduleRelative(state, ToRelative(dueTime), action);
  124. }
  125. /// <summary>
  126. /// Schedules an action to be executed at dueTime.
  127. /// </summary>
  128. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  129. /// <param name="state">State passed to the action to be executed.</param>
  130. /// <param name="dueTime">Absolute time at which to execute the action.</param>
  131. /// <param name="action">Action to be executed.</param>
  132. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  133. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  134. public IDisposable Schedule<TState>(TState state, DateTimeOffset dueTime, Func<IScheduler, TState, IDisposable> action)
  135. {
  136. if (action == null)
  137. throw new ArgumentNullException(nameof(action));
  138. return ScheduleRelative(state, ToRelative(dueTime - Now), action);
  139. }
  140. /// <summary>
  141. /// Starts the virtual time scheduler.
  142. /// </summary>
  143. public void Start()
  144. {
  145. if (!IsEnabled)
  146. {
  147. IsEnabled = true;
  148. do
  149. {
  150. var next = GetNext();
  151. if (next != null)
  152. {
  153. if (Comparer.Compare(next.DueTime, Clock) > 0)
  154. Clock = next.DueTime;
  155. next.Invoke();
  156. }
  157. else
  158. IsEnabled = false;
  159. } while (IsEnabled);
  160. }
  161. }
  162. /// <summary>
  163. /// Stops the virtual time scheduler.
  164. /// </summary>
  165. public void Stop()
  166. {
  167. IsEnabled = false;
  168. }
  169. /// <summary>
  170. /// Advances the scheduler's clock to the specified time, running all work till that point.
  171. /// </summary>
  172. /// <param name="time">Absolute time to advance the scheduler's clock to.</param>
  173. /// <exception cref="ArgumentOutOfRangeException"><paramref name="time"/> is in the past.</exception>
  174. /// <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>
  175. public void AdvanceTo(TAbsolute time)
  176. {
  177. var dueToClock = Comparer.Compare(time, Clock);
  178. if (dueToClock < 0)
  179. throw new ArgumentOutOfRangeException(nameof(time));
  180. if (dueToClock == 0)
  181. return;
  182. if (!IsEnabled)
  183. {
  184. IsEnabled = true;
  185. do
  186. {
  187. var next = GetNext();
  188. if (next != null && Comparer.Compare(next.DueTime, time) <= 0)
  189. {
  190. if (Comparer.Compare(next.DueTime, Clock) > 0)
  191. Clock = next.DueTime;
  192. next.Invoke();
  193. }
  194. else
  195. IsEnabled = false;
  196. } while (IsEnabled);
  197. Clock = time;
  198. }
  199. else
  200. {
  201. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings_Linq.CANT_ADVANCE_WHILE_RUNNING, "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, "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
  252. {
  253. get { return ToDateTimeOffset(Clock); }
  254. }
  255. /// <summary>
  256. /// Gets the next scheduled item to be executed.
  257. /// </summary>
  258. /// <returns>The next scheduled item.</returns>
  259. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "By design. Side-effecting operation to retrieve the next element.")]
  260. protected abstract IScheduledItem<TAbsolute> GetNext();
  261. object IServiceProvider.GetService(Type serviceType)
  262. {
  263. return GetService(serviceType);
  264. }
  265. /// <summary>
  266. /// Discovers scheduler services by interface type. The base class implementation supports
  267. /// only the IStopwatchProvider service. To influence service discovery - such as adding
  268. /// support for other scheduler services - derived types can override this method.
  269. /// </summary>
  270. /// <param name="serviceType">Scheduler service interface type to discover.</param>
  271. /// <returns>Object implementing the requested service, if available; null otherwise.</returns>
  272. protected virtual object GetService(Type serviceType)
  273. {
  274. if (serviceType == typeof(IStopwatchProvider))
  275. return this as IStopwatchProvider;
  276. return null;
  277. }
  278. /// <summary>
  279. /// Starts a new stopwatch object.
  280. /// </summary>
  281. /// <returns>New stopwatch object; started at the time of the request.</returns>
  282. public IStopwatch StartStopwatch()
  283. {
  284. var start = ToDateTimeOffset(Clock);
  285. return new VirtualTimeStopwatch(() => ToDateTimeOffset(Clock) - start);
  286. }
  287. class VirtualTimeStopwatch : IStopwatch
  288. {
  289. private readonly Func<TimeSpan> _getElapsed;
  290. public VirtualTimeStopwatch(Func<TimeSpan> getElapsed)
  291. {
  292. _getElapsed = getElapsed;
  293. }
  294. public TimeSpan Elapsed
  295. {
  296. get { return _getElapsed(); }
  297. }
  298. }
  299. }
  300. /// <summary>
  301. /// Base class for virtual time schedulers using a priority queue for scheduled items.
  302. /// </summary>
  303. /// <typeparam name="TAbsolute">Absolute time representation type.</typeparam>
  304. /// <typeparam name="TRelative">Relative time representation type.</typeparam>
  305. public abstract class VirtualTimeScheduler<TAbsolute, TRelative> : VirtualTimeSchedulerBase<TAbsolute, TRelative>
  306. where TAbsolute : IComparable<TAbsolute>
  307. {
  308. private readonly SchedulerQueue<TAbsolute> queue = new SchedulerQueue<TAbsolute>();
  309. /// <summary>
  310. /// Creates a new virtual time scheduler with the default value of TAbsolute as the initial clock value.
  311. /// </summary>
  312. protected VirtualTimeScheduler()
  313. : base()
  314. {
  315. }
  316. /// <summary>
  317. /// Creates a new virtual time scheduler.
  318. /// </summary>
  319. /// <param name="initialClock">Initial value for the clock.</param>
  320. /// <param name="comparer">Comparer to determine causality of events based on absolute time.</param>
  321. /// <exception cref="ArgumentNullException"><paramref name="comparer"/> is null.</exception>
  322. protected VirtualTimeScheduler(TAbsolute initialClock, IComparer<TAbsolute> comparer)
  323. : base(initialClock, comparer)
  324. {
  325. }
  326. /// <summary>
  327. /// Gets the next scheduled item to be executed.
  328. /// </summary>
  329. /// <returns>The next scheduled item.</returns>
  330. protected override IScheduledItem<TAbsolute> GetNext()
  331. {
  332. lock (queue)
  333. {
  334. while (queue.Count > 0)
  335. {
  336. var next = queue.Peek();
  337. if (next.IsCanceled)
  338. queue.Dequeue();
  339. else
  340. return next;
  341. }
  342. }
  343. return null;
  344. }
  345. /// <summary>
  346. /// Schedules an action to be executed at dueTime.
  347. /// </summary>
  348. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  349. /// <param name="state">State passed to the action to be executed.</param>
  350. /// <param name="action">Action to be executed.</param>
  351. /// <param name="dueTime">Absolute time at which to execute the action.</param>
  352. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  353. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  354. public override IDisposable ScheduleAbsolute<TState>(TState state, TAbsolute dueTime, Func<IScheduler, TState, IDisposable> action)
  355. {
  356. if (action == null)
  357. throw new ArgumentNullException(nameof(action));
  358. var si = default(ScheduledItem<TAbsolute, TState>);
  359. var run = new Func<IScheduler, TState, IDisposable>((scheduler, state1) =>
  360. {
  361. lock (queue)
  362. {
  363. queue.Remove(si);
  364. }
  365. return action(scheduler, state1);
  366. });
  367. si = new ScheduledItem<TAbsolute, TState>(this, state, run, dueTime, Comparer);
  368. lock (queue)
  369. {
  370. queue.Enqueue(si);
  371. }
  372. return Disposable.Create(si.Cancel);
  373. }
  374. }
  375. }