Debian Codegraph @

external/rx/Rx/NET/Source/System.Reactive.Linq/Reactive/Concurrency/VirtualTimeScheduler.cs

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