| 1 |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. |
| 2 |
|
| 3 |
using System; |
| 4 |
using System.Diagnostics; |
| 5 |
using System.Reactive.Disposables; |
| 6 |
using System.Reactive.PlatformServices; |
| 7 |
using System.Threading; |
| 8 |
|
| 9 |
namespace System.Reactive.Concurrency |
| 10 |
{ |
| 11 |
public static partial class Scheduler |
| 12 |
{ |
| 13 |
/// <summary> |
| 14 |
/// Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. |
| 15 |
/// If the scheduler supports periodic scheduling, the request will be forwarded to the periodic scheduling implementation. |
| 16 |
/// If the scheduler provides stopwatch functionality, the periodic task will be emulated using recursive scheduling with a stopwatch to correct for time slippage. |
| 17 |
/// Otherwise, the periodic task will be emulated using recursive scheduling. |
| 18 |
/// </summary> |
| 19 |
/// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam> |
| 20 |
/// <param name="scheduler">The scheduler to run periodic work on.</param> |
| 21 |
/// <param name="state">Initial state passed to the action upon the first iteration.</param> |
| 22 |
/// <param name="period">Period for running the work periodically.</param> |
| 23 |
/// <param name="action">Action to be executed, potentially updating the state.</param> |
| 24 |
/// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns> |
| 25 |
/// <exception cref="ArgumentNullException"><paramref name="scheduler"/> or <paramref name="action"/> is null.</exception> |
| 26 |
/// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than TimeSpan.Zero.</exception> |
| 27 |
public static IDisposable SchedulePeriodic<TState>(this IScheduler scheduler, TState state, TimeSpan period, Func<TState, TState> action) |
| 28 |
{ |
| 29 |
if (scheduler == null) |
| 30 |
throw new ArgumentNullException("scheduler"); |
| 31 |
if (period < TimeSpan.Zero) |
| 32 |
throw new ArgumentOutOfRangeException("period"); |
| 33 |
if (action == null) |
| 34 |
throw new ArgumentNullException("action"); |
| 35 |
|
| 36 |
return SchedulePeriodic_(scheduler, state, period, action); |
| 37 |
} |
| 38 |
|
| 39 |
/// <summary> |
| 40 |
/// Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. |
| 41 |
/// If the scheduler supports periodic scheduling, the request will be forwarded to the periodic scheduling implementation. |
| 42 |
/// If the scheduler provides stopwatch functionality, the periodic task will be emulated using recursive scheduling with a stopwatch to correct for time slippage. |
| 43 |
/// Otherwise, the periodic task will be emulated using recursive scheduling. |
| 44 |
/// </summary> |
| 45 |
/// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam> |
| 46 |
/// <param name="scheduler">Scheduler to execute the action on.</param> |
| 47 |
/// <param name="state">State passed to the action to be executed.</param> |
| 48 |
/// <param name="period">Period for running the work periodically.</param> |
| 49 |
/// <param name="action">Action to be executed.</param> |
| 50 |
/// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns> |
| 51 |
/// <exception cref="ArgumentNullException"><paramref name="scheduler"/> or <paramref name="action"/> is null.</exception> |
| 52 |
/// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than TimeSpan.Zero.</exception> |
| 53 |
public static IDisposable SchedulePeriodic<TState>(this IScheduler scheduler, TState state, TimeSpan period, Action<TState> action) |
| 54 |
{ |
| 55 |
if (scheduler == null) |
| 56 |
throw new ArgumentNullException("scheduler"); |
| 57 |
if (period < TimeSpan.Zero) |
| 58 |
throw new ArgumentOutOfRangeException("period"); |
| 59 |
if (action == null) |
| 60 |
throw new ArgumentNullException("action"); |
| 61 |
|
| 62 |
return SchedulePeriodic_(scheduler, state, period, state_ => { action(state_); return state_; }); |
| 63 |
} |
| 64 |
|
| 65 |
/// <summary> |
| 66 |
/// Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. |
| 67 |
/// If the scheduler supports periodic scheduling, the request will be forwarded to the periodic scheduling implementation. |
| 68 |
/// If the scheduler provides stopwatch functionality, the periodic task will be emulated using recursive scheduling with a stopwatch to correct for time slippage. |
| 69 |
/// Otherwise, the periodic task will be emulated using recursive scheduling. |
| 70 |
/// </summary> |
| 71 |
/// <param name="scheduler">Scheduler to execute the action on.</param> |
| 72 |
/// <param name="period">Period for running the work periodically.</param> |
| 73 |
/// <param name="action">Action to be executed.</param> |
| 74 |
/// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns> |
| 75 |
/// <exception cref="ArgumentNullException"><paramref name="scheduler"/> or <paramref name="action"/> is null.</exception> |
| 76 |
/// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than TimeSpan.Zero.</exception> |
| 77 |
public static IDisposable SchedulePeriodic(this IScheduler scheduler, TimeSpan period, Action action) |
| 78 |
{ |
| 79 |
if (scheduler == null) |
| 80 |
throw new ArgumentNullException("scheduler"); |
| 81 |
if (period < TimeSpan.Zero) |
| 82 |
throw new ArgumentOutOfRangeException("period"); |
| 83 |
if (action == null) |
| 84 |
throw new ArgumentNullException("action"); |
| 85 |
|
| 86 |
return SchedulePeriodic_(scheduler, action, period, a => { a(); return a; }); |
| 87 |
} |
| 88 |
|
| 89 |
/// <summary> |
| 90 |
/// Starts a new stopwatch object by dynamically discovering the scheduler's capabilities. |
| 91 |
/// If the scheduler provides stopwatch functionality, the request will be forwarded to the stopwatch provider implementation. |
| 92 |
/// Otherwise, the stopwatch will be emulated using the scheduler's notion of absolute time. |
| 93 |
/// </summary> |
| 94 |
/// <param name="scheduler">Scheduler to obtain a stopwatch for.</param> |
| 95 |
/// <returns>New stopwatch object; started at the time of the request.</returns> |
| 96 |
/// <exception cref="ArgumentNullException"><paramref name="scheduler"/> is null.</exception> |
| 97 |
/// <remarks>The resulting stopwatch object can have non-monotonic behavior.</remarks> |
| 98 |
public static IStopwatch StartStopwatch(this IScheduler scheduler) |
| 99 |
{ |
| 100 |
if (scheduler == null) |
| 101 |
throw new ArgumentNullException("scheduler"); |
| 102 |
|
| 103 |
// |
| 104 |
// All schedulers deriving from LocalScheduler will automatically pick up this |
| 105 |
// capability based on a local stopwatch, typically using QueryPerformanceCounter |
| 106 |
// through the System.Diagnostics.Stopwatch class. |
| 107 |
// |
| 108 |
// Notice virtual time schedulers do implement this facility starting from Rx v2.0, |
| 109 |
// using subtraction of their absolute time notion to compute elapsed time values. |
| 110 |
// This is fine because those schedulers do not allow the clock to go back in time. |
| 111 |
// |
| 112 |
// For schedulers that don't have a stopwatch, we have to pick some fallback logic |
| 113 |
// here. We could either dismiss the scheduler's notion of time and go for the CAL's |
| 114 |
// stopwatch facility, or go with a stopwatch based on "scheduler.Now", which has |
| 115 |
// the drawback of potentially going back in time: |
| 116 |
// |
| 117 |
// - Using the CAL's stopwatch facility causes us to abondon the scheduler's |
| 118 |
// potentially virtualized notion of time, always going for the local system |
| 119 |
// time instead. |
| 120 |
// |
| 121 |
// - Using the scheduler's Now property for calculations can break monotonicity, |
| 122 |
// and there's no right answer on how to deal with jumps back in time. |
| 123 |
// |
| 124 |
// However, even the built-in stopwatch in the BCL can potentially fall back to |
| 125 |
// subtraction of DateTime values in case no high-resolution performance counter is |
| 126 |
// available, causing monotonicity to break down. We're not trying to solve this |
| 127 |
// problem there either (though we could check IsHighResolution and smoothen out |
| 128 |
// non-monotonic points somehow), so we pick the latter option as the lesser of |
| 129 |
// two evils (also because it should occur rarely). |
| 130 |
// |
| 131 |
// Users of the stopwatch retrieved by this method could detect non-sensical data |
| 132 |
// revealing a jump back in time, or implement custom fallback logic like the one |
| 133 |
// shown below. |
| 134 |
// |
| 135 |
var swp = scheduler.AsStopwatchProvider(); |
| 136 |
if (swp != null) |
| 137 |
return swp.StartStopwatch(); |
| 138 |
|
| 139 |
return new EmulatedStopwatch(scheduler); |
| 140 |
} |
| 141 |
|
| 142 |
private static IDisposable SchedulePeriodic_<TState>(IScheduler scheduler, TState state, TimeSpan period, Func<TState, TState> action) |
| 143 |
{ |
| 144 |
// |
| 145 |
// Design rationale: |
| 146 |
// |
| 147 |
// In Rx v1.x, we employed recursive scheduling for periodic tasks. The following code |
| 148 |
// fragment shows how the Timer (and hence Interval) function used to be implemented: |
| 149 |
// |
| 150 |
// var p = Normalize(period); |
| 151 |
// |
| 152 |
// return new AnonymousObservable<long>(observer => |
| 153 |
// { |
| 154 |
// var d = dueTime; |
| 155 |
// long count = 0; |
| 156 |
// return scheduler.Schedule(d, self => |
| 157 |
// { |
| 158 |
// if (p > TimeSpan.Zero) |
| 159 |
// { |
| 160 |
// var now = scheduler.Now; |
| 161 |
// d = d + p; |
| 162 |
// if (d <= now) |
| 163 |
// d = now + p; |
| 164 |
// } |
| 165 |
// |
| 166 |
// observer.OnNext(count); |
| 167 |
// count = unchecked(count + 1); |
| 168 |
// self(d); |
| 169 |
// }); |
| 170 |
// }); |
| 171 |
// |
| 172 |
// Despite the purity of this approach, it suffered from a set of drawbacks: |
| 173 |
// |
| 174 |
// 1) Usage of IScheduler.Now to correct for time drift did have a positive effect for |
| 175 |
// a limited number of scenarios, in particular when a short period was used. The |
| 176 |
// major issues with this are: |
| 177 |
// |
| 178 |
// a) Relying on absolute time at the LINQ layer in Rx's layer map, causing issues |
| 179 |
// when the system clock changes. Various customers hit this issue, reported to |
| 180 |
// us on the MSDN forums. Basically, when the clock goes forward, the recursive |
| 181 |
// loop wants to catch up as quickly as it can; when it goes backwards, a long |
| 182 |
// silence will occur. (See 2 for a discussion of WP7 related fixes.) |
| 183 |
// |
| 184 |
// b) Even if a) would be addressed by using Rx v2.0's capabilities to monitor for |
| 185 |
// system clock changes, the solution would violate the reasonable expectation |
| 186 |
// of operators overloads using TimeSpan *not* relying on absolute time. |
| 187 |
// |
| 188 |
// c) Drift correction doesn't work for large periods when the system encounters |
| 189 |
// systematic drift. For example, in the lab we've seen cases of drift up to |
| 190 |
// tens of seconds on a 24 hour timeframe. Correcting for this drift by making |
| 191 |
// a recursive call with a due time of 24 * 3600 with 10 seconds of adjustment |
| 192 |
// won't fix systematic drift. |
| 193 |
// |
| 194 |
// 2) This implementation has been plagued with issues around application container |
| 195 |
// lifecycle models, in particular Windows Phone 7's model of tombstoning and in |
| 196 |
// particular its "dormant state". This feature was introduced in Mango to enable |
| 197 |
// fast application switching. Essentially, the phone's OS puts the application |
| 198 |
// in a suspended state when the user navigates "forward" (or takes an incoming |
| 199 |
// call for instance). When the application is woken up again, threads are resumed |
| 200 |
// and we're faced with an illusion of missed events due to the use of absolute |
| 201 |
// time, not relative to how the application observes it. This caused nightmare |
| 202 |
// scenarios of fast battery drain due to the flood of catch-up work. |
| 203 |
// |
| 204 |
// See http://msdn.microsoft.com/en-us/library/ff817008(v=vs.92).aspx for more |
| 205 |
// information on this. |
| 206 |
// |
| 207 |
// 3) Recursive scheduling imposes a non-trivial cost due to the creation of many |
| 208 |
// single-shot timers and closures. For high frequency timers, this can cause a |
| 209 |
// lot of churn in the GC, which we like to avoid (operators shouldn't have hidden |
| 210 |
// linear - or worse - allocation cost). |
| 211 |
// |
| 212 |
// Notice these drawbacks weren't limited to the use of Timer and Interval directly, |
| 213 |
// as many operators such as Sample, Buffer, and Window used such sequences for their |
| 214 |
// periodic behavior (typically by delegating to a more general overload). |
| 215 |
// |
| 216 |
// As a result, in Rx v2.0, we took the decision to improve periodic timing based on |
| 217 |
// the following design decisions: |
| 218 |
// |
| 219 |
// 1) When the scheduler has the ability to run a periodic task, it should implement |
| 220 |
// the ISchedulerPeriodic interface and expose it through the IServiceProvider |
| 221 |
// interface. Passing the intent of the user through all layers of Rx, down to the |
| 222 |
// underlying infrastructure provides delegation of responsibilities. This allows |
| 223 |
// the target scheduler to optimize execution in various ways, e.g. by employing |
| 224 |
// techniques such as timer coalescing. |
| 225 |
// |
| 226 |
// See http://www.bing.com/search?q=windows+timer+coalescing for information on |
| 227 |
// techniques like timer coalescing which may be applied more aggressively in |
| 228 |
// future OS releases in order to reduce power consumption. |
| 229 |
// |
| 230 |
// 2) Emulation of periodic scheduling is used to avoid breaking existing code that |
| 231 |
// uses schedulers without this capability. We expect those fallback paths to be |
| 232 |
// exercised rarely, though the use of DisableOptimizations can trigger them as |
| 233 |
// well. In such cases we rely on stopwatches or a carefully crafted recursive |
| 234 |
// scheme to deal with (or maximally compensate for) slippage or time. Behavior |
| 235 |
// of periodic tasks is expected to be as follows: |
| 236 |
// |
| 237 |
// timer ticks 0-------1-------2-------3-------4-------5-------6----... |
| 238 |
// | | | +====+ +==+ | | |
| 239 |
// user code +~~~| +~| +~~~~~~~~~~~|+~~~~|+~~| +~~~| +~~| |
| 240 |
// |
| 241 |
// rather than the following scheme, where time slippage is introduced by user |
| 242 |
// code running on the scheduler: |
| 243 |
// |
| 244 |
// timer ticks 0####-------1##-------2############-------3#####-----... |
| 245 |
// | | | | |
| 246 |
// user code +~~~| +~| +~~~~~~~~~~~| +~~~~| |
| 247 |
// |
| 248 |
// (Side-note: Unfortunately, we didn't reserve the name Interval for the latter |
| 249 |
// behavior, but used it as an alias for "periodic scheduling" with |
| 250 |
// the former behavior, delegating to the Timer implementation. One |
| 251 |
// can simulate this behavior using Generate, which uses tail calls.) |
| 252 |
// |
| 253 |
// This behavior is important for operations like Sample, Buffer, and Window, all |
| 254 |
// of which expect proper spacing of events, even if the user code takes a long |
| 255 |
// time to complete (considered a bad practice nonetheless, cf. ObserveOn). |
| 256 |
// |
| 257 |
// 3) To deal with the issue of suspensions induced by application lifecycle events |
| 258 |
// in Windows Phone and WinRT applications, we decided to hook available system |
| 259 |
// events through IHostLifecycleNotifications, discovered through the PEP in order |
| 260 |
// to maintain portability of the core of Rx. |
| 261 |
// |
| 262 |
var periodic = scheduler.AsPeriodic(); |
| 263 |
if (periodic != null) |
| 264 |
{ |
| 265 |
return periodic.SchedulePeriodic(state, period, action); |
| 266 |
} |
| 267 |
|
| 268 |
var swp = scheduler.AsStopwatchProvider(); |
| 269 |
if (swp != null) |
| 270 |
{ |
| 271 |
var spr = new SchedulePeriodicStopwatch<TState>(scheduler, state, period, action, swp); |
| 272 |
return spr.Start(); |
| 273 |
} |
| 274 |
else |
| 275 |
{ |
| 276 |
var spr = new SchedulePeriodicRecursive<TState>(scheduler, state, period, action); |
| 277 |
return spr.Start(); |
| 278 |
} |
| 279 |
} |
| 280 |
|
| 281 |
class SchedulePeriodicStopwatch<TState> |
| 282 |
{ |
| 283 |
private readonly IScheduler _scheduler; |
| 284 |
private readonly TimeSpan _period; |
| 285 |
private readonly Func<TState, TState> _action; |
| 286 |
private readonly IStopwatchProvider _stopwatchProvider; |
| 287 |
|
| 288 |
public SchedulePeriodicStopwatch(IScheduler scheduler, TState state, TimeSpan period, Func<TState, TState> action, IStopwatchProvider stopwatchProvider) |
| 289 |
{ |
| 290 |
_scheduler = scheduler; |
| 291 |
_period = period; |
| 292 |
_action = action; |
| 293 |
_stopwatchProvider = stopwatchProvider; |
| 294 |
|
| 295 |
_state = state; |
| 296 |
_runState = STOPPED; |
| 297 |
} |
| 298 |
|
| 299 |
private TState _state; |
| 300 |
|
| 301 |
private readonly object _gate = new object(); |
| 302 |
private readonly AutoResetEvent _resumeEvent = new AutoResetEvent(false); |
| 303 |
private volatile int _runState; |
| 304 |
private IStopwatch _stopwatch; |
| 305 |
private TimeSpan _nextDue; |
| 306 |
private TimeSpan _suspendedAt; |
| 307 |
private TimeSpan _inactiveTime; |
| 308 |
|
| 309 |
// |
| 310 |
// State transition diagram: |
| 311 |
// (c) |
| 312 |
// +-----------<-----------+ |
| 313 |
// / \ |
| 314 |
// / (b) \ |
| 315 |
// | +-->--SUSPENDED---+ |
| 316 |
// (a) v / | |
| 317 |
// ^----STOPPED -->-- RUNNING -->--+ v (e) |
| 318 |
// \ | |
| 319 |
// +-->--DISPOSED----$ |
| 320 |
// (d) |
| 321 |
// |
| 322 |
// (a) Start --> call to Schedule the Tick method |
| 323 |
// (b) Suspending event handler --> Tick gets blocked waiting for _resumeEvent |
| 324 |
// (c) Resuming event handler --> _resumeEvent is signaled, Tick continues |
| 325 |
// (d) Dispose returned object from Start --> scheduled work is cancelled |
| 326 |
// (e) Dispose returned object from Start --> unblocks _resumeEvent, Tick exits |
| 327 |
// |
| 328 |
private const int STOPPED = 0; |
| 329 |
private const int RUNNING = 1; |
| 330 |
private const int SUSPENDED = 2; |
| 331 |
private const int DISPOSED = 3; |
| 332 |
|
| 333 |
public IDisposable Start() |
| 334 |
{ |
| 335 |
RegisterHostLifecycleEventHandlers(); |
| 336 |
|
| 337 |
_stopwatch = _stopwatchProvider.StartStopwatch(); |
| 338 |
_nextDue = _period; |
| 339 |
_runState = RUNNING; |
| 340 |
|
| 341 |
return new CompositeDisposable(2) |
| 342 |
{ |
| 343 |
_scheduler.Schedule(_nextDue, Tick), |
| 344 |
Disposable.Create(Cancel) |
| 345 |
}; |
| 346 |
} |
| 347 |
|
| 348 |
private void Tick(Action<TimeSpan> recurse) |
| 349 |
{ |
| 350 |
_nextDue += _period; |
| 351 |
_state = _action(_state); |
| 352 |
|
| 353 |
var next = default(TimeSpan); |
| 354 |
|
| 355 |
while (true) |
| 356 |
{ |
| 357 |
var shouldWaitForResume = false; |
| 358 |
|
| 359 |
lock (_gate) |
| 360 |
{ |
| 361 |
if (_runState == RUNNING) |
| 362 |
{ |
| 363 |
// |
| 364 |
// This is the fast path. We just let the stopwatch continue to |
| 365 |
// run while we're suspended, but compensate for time that was |
| 366 |
// recorded as inactive based on cumulative deltas computed in |
| 367 |
// the suspend and resume event handlers. |
| 368 |
// |
| 369 |
next = Normalize(_nextDue - (_stopwatch.Elapsed - _inactiveTime)); |
| 370 |
break; |
| 371 |
} |
| 372 |
else if (_runState == DISPOSED) |
| 373 |
{ |
| 374 |
// |
| 375 |
// In case the periodic job gets disposed but we are currently |
| 376 |
// waiting to come back out of suspension, we should make sure |
| 377 |
// we don't remain blocked indefinitely. Hence, we set the event |
| 378 |
// in the Cancel method and trap this case here to bail out from |
| 379 |
// the scheduled work gracefully. |
| 380 |
// |
| 381 |
return; |
| 382 |
} |
| 383 |
else |
| 384 |
{ |
| 385 |
// |
| 386 |
// This is the least common case where we got suspended and need |
| 387 |
// to block such that future reevaluations of the next due time |
| 388 |
// will pick up the cumulative inactive time delta. |
| 389 |
// |
| 390 |
Debug.Assert(_runState == SUSPENDED); |
| 391 |
shouldWaitForResume = true; |
| 392 |
} |
| 393 |
} |
| 394 |
|
| 395 |
// |
| 396 |
// Only happens in the SUSPENDED case; otherwise we will have broken from |
| 397 |
// the loop or have quit the Tick method. After returning from the wait, |
| 398 |
// we'll either be RUNNING again, quit due to a DISPOSED transition, or |
| 399 |
// be extremely unlucky to find ourselves SUSPENDED again and be blocked |
| 400 |
// once more. |
| 401 |
// |
| 402 |
if (shouldWaitForResume) |
| 403 |
_resumeEvent.WaitOne(); |
| 404 |
} |
| 405 |
|
| 406 |
recurse(next); |
| 407 |
} |
| 408 |
|
| 409 |
private void Cancel() |
| 410 |
{ |
| 411 |
UnregisterHostLifecycleEventHandlers(); |
| 412 |
|
| 413 |
lock (_gate) |
| 414 |
{ |
| 415 |
_runState = DISPOSED; |
| 416 |
|
| 417 |
if (!Environment.HasShutdownStarted) |
| 418 |
_resumeEvent.Set(); |
| 419 |
} |
| 420 |
} |
| 421 |
|
| 422 |
private void Suspending(object sender, HostSuspendingEventArgs args) |
| 423 |
{ |
| 424 |
// |
| 425 |
// The host is telling us we're about to be suspended. At this point, time |
| 426 |
// computations will still be in a valid range (next <= _period), but after |
| 427 |
// we're woken up again, Tick would start to go on a crucade to catch up. |
| 428 |
// |
| 429 |
// This has caused problems in the past, where the flood of events caused |
| 430 |
// batteries to drain etc (see design rationale discussion higher up). |
| 431 |
// |
| 432 |
// In order to mitigate this problem, we force Tick to suspend before its |
| 433 |
// next computation of the next due time. Notice we can't afford to block |
| 434 |
// during the Suspending event handler; the host expects us to respond to |
| 435 |
// this event quickly, such that we're not keeping the application from |
| 436 |
// suspending promptly. |
| 437 |
// |
| 438 |
lock (_gate) |
| 439 |
{ |
| 440 |
if (_runState == RUNNING) |
| 441 |
{ |
| 442 |
_suspendedAt = _stopwatch.Elapsed; |
| 443 |
_runState = SUSPENDED; |
| 444 |
|
| 445 |
if (!Environment.HasShutdownStarted) |
| 446 |
_resumeEvent.Reset(); |
| 447 |
} |
| 448 |
} |
| 449 |
} |
| 450 |
|
| 451 |
private void Resuming(object sender, HostResumingEventArgs args) |
| 452 |
{ |
| 453 |
// |
| 454 |
// The host is telling us we're being resumed. At this point, code will |
| 455 |
// already be running in the process, so a past timer may still expire and |
| 456 |
// cause the code in Tick to run. Two interleavings are possible now: |
| 457 |
// |
| 458 |
// 1) We enter the gate first, and will adjust the cumulative inactive |
| 459 |
// time delta used for correction. The code in Tick will have the |
| 460 |
// illusion nothing happened and find itself RUNNING when entering |
| 461 |
// the gate, resuming activities as before. |
| 462 |
// |
| 463 |
// 2) The code in Tick enters the gate first, and takes notice of the |
| 464 |
// currently SUSPENDED state. It leaves the gate, entering the wait |
| 465 |
// state for _resumeEvent. Next, we enter to adjust the cumulative |
| 466 |
// inactive time delta, switch to the RUNNING state and signal the |
| 467 |
// event for Tick to carry on and recompute its next due time based |
| 468 |
// on the new cumulative delta. |
| 469 |
// |
| 470 |
lock (_gate) |
| 471 |
{ |
| 472 |
if (_runState == SUSPENDED) |
| 473 |
{ |
| 474 |
_inactiveTime += _stopwatch.Elapsed - _suspendedAt; |
| 475 |
_runState = RUNNING; |
| 476 |
|
| 477 |
if (!Environment.HasShutdownStarted) |
| 478 |
_resumeEvent.Set(); |
| 479 |
} |
| 480 |
} |
| 481 |
} |
| 482 |
|
| 483 |
private void RegisterHostLifecycleEventHandlers() |
| 484 |
{ |
| 485 |
HostLifecycleService.Suspending += Suspending; |
| 486 |
HostLifecycleService.Resuming += Resuming; |
| 487 |
HostLifecycleService.AddRef(); |
| 488 |
} |
| 489 |
|
| 490 |
private void UnregisterHostLifecycleEventHandlers() |
| 491 |
{ |
| 492 |
HostLifecycleService.Suspending -= Suspending; |
| 493 |
HostLifecycleService.Resuming -= Resuming; |
| 494 |
HostLifecycleService.Release(); |
| 495 |
} |
| 496 |
} |
| 497 |
|
| 498 |
class SchedulePeriodicRecursive<TState> |
| 499 |
{ |
| 500 |
private readonly IScheduler _scheduler; |
| 501 |
private readonly TimeSpan _period; |
| 502 |
private readonly Func<TState, TState> _action; |
| 503 |
|
| 504 |
public SchedulePeriodicRecursive(IScheduler scheduler, TState state, TimeSpan period, Func<TState, TState> action) |
| 505 |
{ |
| 506 |
_scheduler = scheduler; |
| 507 |
_period = period; |
| 508 |
_action = action; |
| 509 |
|
| 510 |
_state = state; |
| 511 |
} |
| 512 |
|
| 513 |
private TState _state; |
| 514 |
private int _pendingTickCount; |
| 515 |
private IDisposable _cancel; |
| 516 |
|
| 517 |
public IDisposable Start() |
| 518 |
{ |
| 519 |
_pendingTickCount = 0; |
| 520 |
|
| 521 |
var d = new SingleAssignmentDisposable(); |
| 522 |
_cancel = d; |
| 523 |
|
| 524 |
d.Disposable = _scheduler.Schedule(TICK, _period, Tick); |
| 525 |
|
| 526 |
return d; |
| 527 |
} |
| 528 |
|
| 529 |
// |
| 530 |
// The protocol using the three commands is explained in the Tick implementation below. |
| 531 |
// |
| 532 |
private const int TICK = 0; |
| 533 |
private const int DISPATCH_START = 1; |
| 534 |
private const int DISPATCH_END = 2; |
| 535 |
|
| 536 |
private void Tick(int command, Action<int, TimeSpan> recurse) |
| 537 |
{ |
| 538 |
switch (command) |
| 539 |
{ |
| 540 |
case TICK: |
| 541 |
// |
| 542 |
// Ticks keep going at the specified periodic rate. We do a head call such |
| 543 |
// that no slippage is introduced because of DISPATCH_START work involving |
| 544 |
// user code that may take arbitrarily long. |
| 545 |
// |
| 546 |
recurse(TICK, _period); |
| 547 |
|
| 548 |
// |
| 549 |
// If we're not transitioning from 0 to 1 pending tick, another processing |
| 550 |
// request is in flight which will see a non-zero pending tick count after |
| 551 |
// doing the final decrement, causing it to reschedule immediately. We can |
| 552 |
// safely bail out, delegating work to the catch-up tail calls. |
| 553 |
// |
| 554 |
if (Interlocked.Increment(ref _pendingTickCount) == 1) |
| 555 |
goto case DISPATCH_START; |
| 556 |
|
| 557 |
break; |
| 558 |
|
| 559 |
case DISPATCH_START: |
| 560 |
try |
| 561 |
{ |
| 562 |
_state = _action(_state); |
| 563 |
} |
| 564 |
catch (Exception e) |
| 565 |
{ |
| 566 |
_cancel.Dispose(); |
| 567 |
e.Throw(); |
| 568 |
} |
| 569 |
|
| 570 |
// |
| 571 |
// This is very subtle. We can't do a goto case DISPATCH_END here because it |
| 572 |
// wouldn't introduce interleaving of periodic ticks that are due. In order |
| 573 |
// to have best effort behavior for schedulers that don't have concurrency, |
| 574 |
// we yield by doing a recursive call here. Notice this doesn't heal all of |
| 575 |
// the problem, because the TICK commands that may be dispatched before the |
| 576 |
// scheduled DISPATCH_END will do a "recurse(TICK, period)", which is relative |
| 577 |
// from the point of entrance. Really all we're doing here is damage control |
| 578 |
// for the case there's no stopwatch provider which should be rare (notice |
| 579 |
// the LocalScheduler base class always imposes a stopwatch, but it can get |
| 580 |
// disabled using DisableOptimizations; legacy implementations of schedulers |
| 581 |
// from the v1.x days will not have a stopwatch). |
| 582 |
// |
| 583 |
recurse(DISPATCH_END, TimeSpan.Zero); |
| 584 |
|
| 585 |
break; |
| 586 |
|
| 587 |
case DISPATCH_END: |
| 588 |
// |
| 589 |
// If work was due while we were still running user code, the count will have |
| 590 |
// been incremented by the periodic tick handler above. In that case, we will |
| 591 |
// reschedule ourselves for dispatching work immediately. |
| 592 |
// |
| 593 |
// Notice we don't run a loop here, in order to allow interleaving of work on |
| 594 |
// the scheduler by making recursive calls. In case we would use AsyncLock to |
| 595 |
// ensure serialized execution the owner could get stuck in such a loop, thus |
| 596 |
// we make tail calls to play nice with the scheduler. |
| 597 |
// |
| 598 |
if (Interlocked.Decrement(ref _pendingTickCount) > 0) |
| 599 |
recurse(DISPATCH_START, TimeSpan.Zero); |
| 600 |
|
| 601 |
break; |
| 602 |
} |
| 603 |
} |
| 604 |
} |
| 605 |
|
| 606 |
class EmulatedStopwatch : IStopwatch |
| 607 |
{ |
| 608 |
private readonly IScheduler _scheduler; |
| 609 |
private readonly DateTimeOffset _start; |
| 610 |
|
| 611 |
public EmulatedStopwatch(IScheduler scheduler) |
| 612 |
{ |
| 613 |
_scheduler = scheduler; |
| 614 |
_start = _scheduler.Now; |
| 615 |
} |
| 616 |
|
| 617 |
public TimeSpan Elapsed |
| 618 |
{ |
| 619 |
get { return Scheduler.Normalize(_scheduler.Now - _start); } |
| 620 |
} |
| 621 |
} |
| 622 |
} |
| 623 |
} |