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