VirtualTimeScheduler.cs 17 KB

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