Debian Codegraph @

external/rx/Rx/NET/Source/System.Reactive.Core/Reactive/Concurrency/LocalScheduler.TimerQueue.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.Reactive.Disposables;
5 using System.Reactive.PlatformServices;
6 using System.Threading;
7
8 namespace System.Reactive.Concurrency
9 {
10 public partial class LocalScheduler
11 {
12 /// <summary>
13 /// Gate to protect queues and to synchronize scheduling decisions and system clock
14 /// change management.
15 /// </summary>
16 private static readonly object s_gate = new object();
17
18 /// <summary>
19 /// Long term work queue. Contains work that's due beyond SHORTTERM, computed at the
20 /// time of enqueueing.
21 /// </summary>
22 private static readonly PriorityQueue<WorkItem/*!*/> s_longTerm = new PriorityQueue<WorkItem/*!*/>();
23
24 /// <summary>
25 /// Disposable resource for the long term timer that will reevaluate and dispatch the
26 /// first item in the long term queue. A serial disposable is used to make "dispose
27 /// current and assign new" logic easier. The disposable itself is never disposed.
28 /// </summary>
29 private static readonly SerialDisposable s_nextLongTermTimer = new SerialDisposable();
30
31 /// <summary>
32 /// Item at the head of the long term queue for which the current long term timer is
33 /// running. Used to detect changes in the queue and decide whether we should replace
34 /// or can continue using the current timer (because no earlier long term work was
35 /// added to the queue).
36 /// </summary>
37 private static WorkItem s_nextLongTermWorkItem = null;
38
39 /// <summary>
40 /// Short term work queue. Contains work that's due soon, computed at the time of
41 /// enqueueing or upon reevaluation of the long term queue causing migration of work
42 /// items. This queue is kept in order to be able to relocate short term items back
43 /// to the long term queue in case a system clock change occurs.
44 /// </summary>
45 private static readonly PriorityQueue<WorkItem/*!*/> s_shortTerm = new PriorityQueue<WorkItem/*!*/>();
46
47 /// <summary>
48 /// Set of disposable handles to all of the current short term work Schedule calls,
49 /// allowing those to be cancelled upon a system clock change.
50 /// </summary>
51 #if !NO_HASHSET
52 private static readonly HashSet<IDisposable> s_shortTermWork = new HashSet<IDisposable>();
53 #else
54 private static readonly Dictionary<IDisposable, object> s_shortTermWork = new Dictionary<IDisposable, object>();
55 #endif
56
57 /// <summary>
58 /// Threshold where an item is considered to be short term work or gets moved from
59 /// long term to short term.
60 /// </summary>
61 private static readonly TimeSpan SHORTTERM = TimeSpan.FromSeconds(10);
62
63 /// <summary>
64 /// Maximum error ratio for timer drift. We've seen machines with 10s drift on a
65 /// daily basis, which is in the order 10E-4, so we allow for extra margin here.
66 /// This value is used to calculate early arrival for the long term queue timer
67 /// that will reevaluate work for the short term queue.
68 ///
69 /// Example: -------------------------------...---------------------*-----$
70 /// ^ ^
71 /// | |
72 /// early due
73 /// 0.999 1.0
74 ///
75 /// We also make the gap between early and due at least LONGTOSHORT so we have
76 /// enough time to transition work to short term and as a courtesy to the
77 /// destination scheduler to manage its queues etc.
78 /// </summary>
79 private const int MAXERRORRATIO = 1000;
80
81 /// <summary>
82 /// Minimum threshold for the long term timer to fire before the queue is reevaluated
83 /// for short term work. This value is chosen to be less than SHORTTERM in order to
84 /// ensure the timer fires and has work to transition to the short term queue.
85 /// </summary>
86 private static readonly TimeSpan LONGTOSHORT = TimeSpan.FromSeconds(5);
87
88 /// <summary>
89 /// Threshold used to determine when a short term timer has fired too early compared
90 /// to the absolute due time. This provides a last chance protection against early
91 /// completion of scheduled work, which can happen in case of time adjustment in the
92 /// operating system (cf. GetSystemTimeAdjustment).
93 /// </summary>
94 private static readonly TimeSpan RETRYSHORT = TimeSpan.FromMilliseconds(50);
95
96 /// <summary>
97 /// Longest interval supported by <see cref="System.Threading.Timer"/>.
98 /// </summary>
99 private static readonly TimeSpan MAXSUPPORTEDTIMER = TimeSpan.FromMilliseconds((1L << 32) - 2);
100
101 [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "We can't really lift this into a field initializer, and would end up checking for an initialization flag in every static method anyway (which is roughly what the JIT does in a thread-safe manner).")]
102 static LocalScheduler()
103 {
104 //
105 // Hook up for system clock change notifications. This doesn't do anything until the
106 // AddRef method is called (which can throw).
107 //
108 SystemClock.SystemClockChanged += SystemClockChanged;
109 }
110
111 /// <summary>
112 /// Enqueues absolute time scheduled work in the timer queue or the short term work list.
113 /// </summary>
114 /// <param name="scheduler">Scheduler to run the work on. Typically "this" from the caller's perspective (LocalScheduler.Schedule), but parameter kept because we have a single (static) timer queue across all of Rx local schedulers.</param>
115 /// <param name="state">State to pass to the action.</param>
116 /// <param name="dueTime">Absolute time to run the work on. The timer queue is responsible to execute the work close to the specified time, also accounting for system clock changes.</param>
117 /// <param name="action">Action to run, potentially recursing into the scheduler.</param>
118 /// <returns>Disposable object to prevent the work from running.</returns>
119 private static IDisposable Enqueue<TState>(IScheduler scheduler, TState state, DateTimeOffset dueTime, Func<IScheduler, TState, IDisposable> action)
120 {
121 //
122 // Work that's due in the past is sent to the underlying scheduler through the Schedule
123 // overload for execution at TimeSpan.Zero. We don't go to the overload for immediate
124 // scheduling in order to:
125 //
126 // - Preserve the time-based nature of the call as surfaced to the underlying scheduler,
127 // as it may use different queuing strategies.
128 //
129 // - Optimize for the default behavior of LocalScheduler where a virtual call to Schedule
130 // for immediate execution calls into the abstract Schedule method with TimeSpan.Zero.
131 //
132 var due = Scheduler.Normalize(dueTime - scheduler.Now);
133 if (due == TimeSpan.Zero)
134 {
135 return scheduler.Schedule<TState>(state, TimeSpan.Zero, action);
136 }
137
138 //
139 // We're going down the path of queueing up work or scheduling it, so we need to make
140 // sure we can get system clock change notifications. If not, the call below is expected
141 // to throw NotSupportedException. WorkItem.Invoke decreases the ref count again to allow
142 // the system clock monitor to stop if there's no work left. Notice work items always
143 // reach an execution stage since we don't dequeue items but merely mark them as cancelled
144 // through WorkItem.Dispose. Double execution is also prevented, so the ref count should
145 // correctly balance out.
146 //
147 SystemClock.AddRef();
148
149 var workItem = new WorkItem<TState>(scheduler, state, dueTime, action);
150
151 if (due <= SHORTTERM)
152 {
153 ScheduleShortTermWork(workItem);
154 }
155 else
156 {
157 ScheduleLongTermWork(workItem);
158 }
159
160 return workItem;
161 }
162
163 /// <summary>
164 /// Schedule work that's due in the short term. This leads to relative scheduling calls to the
165 /// underlying scheduler for short TimeSpan values. If the system clock changes in the meantime,
166 /// the short term work is attempted to be cancelled and reevaluated.
167 /// </summary>
168 /// <param name="item">Work item to schedule in the short term. The caller is responsible to determine the work is indeed short term.</param>
169 private static void ScheduleShortTermWork(WorkItem/*!*/ item)
170 {
171 lock (s_gate)
172 {
173 s_shortTerm.Enqueue(item);
174
175 //
176 // We don't bother trying to dequeue the item or stop the timer upon cancellation,
177 // but always let the timer fire to do the queue maintenance. When the item is
178 // cancelled, it won't run (see WorkItem.Invoke). In the event of a system clock
179 // change, all outstanding work in s_shortTermWork is cancelled and the short
180 // term queue is reevaluated, potentially prompting rescheduling of short term
181 // work. Notice work is protected against double execution by the implementation
182 // of WorkItem.Invoke.
183 //
184 var d = new SingleAssignmentDisposable();
185 #if !NO_HASHSET
186 s_shortTermWork.Add(d);
187 #else
188 s_shortTermWork.Add(d, null);
189 #endif
190
191 //
192 // We normalize the time delta again (possibly redundant), because we can't assume
193 // the underlying scheduler implementations is valid and deals with negative values
194 // (though it should).
195 //
196 var dueTime = Scheduler.Normalize(item.DueTime - item.Scheduler.Now);
197 d.Disposable = item.Scheduler.Schedule(d, dueTime, ExecuteNextShortTermWorkItem);
198 }
199 }
200
201 /// <summary>
202 /// Callback to process the next short term work item.
203 /// </summary>
204 /// <param name="scheduler">Recursive scheduler supplied by the underlying scheduler.</param>
205 /// <param name="cancel">Disposable used to identify the work the timer was triggered for (see code for usage).</param>
206 /// <returns>Empty disposable. Recursive work cancellation is wired through the original WorkItem.</returns>
207 private static IDisposable ExecuteNextShortTermWorkItem(IScheduler scheduler, IDisposable cancel)
208 {
209 var next = default(WorkItem);
210
211 lock (s_gate)
212 {
213 //
214 // Notice that even though we try to cancel all work in the short term queue upon a
215 // system clock change, cancellation may not be honored immediately and there's a
216 // small chance this code runs for work that has been cancelled. Because the handler
217 // doesn't execute the work that triggered the time-based Schedule call, but always
218 // runs the work from the short term queue in order, we need to make sure we're not
219 // stealing items in the queue. We can do so by remembering the object identity of
220 // the disposable and check whether it still exists in the short term work list. If
221 // not, a system clock change handler has gotten rid of it as part of reevaluating
222 // the short term queue, but we still ended up here because the inherent race in the
223 // call to Dispose versus the underlying timer. It's also possible the underlying
224 // scheduler does a bad job at cancellation, so this measure helps for that too.
225 //
226 if (s_shortTermWork.Remove(cancel) && s_shortTerm.Count > 0)
227 {
228 next = s_shortTerm.Dequeue();
229 }
230 }
231
232 if (next != null)
233 {
234 //
235 // If things don't make sense and we're way too early to run the work, this is our
236 // final chance to prevent us from running before the due time. This situation can
237 // arise when Windows applies system clock adjustment (see SetSystemTimeAdjustment)
238 // and as a result the clock is ticking slower. If the clock is ticking faster due
239 // to such an adjustment, too bad :-). We try to minimize the window for the final
240 // relative time based scheduling such that 10%+ adjustments to the clock rate
241 // have only "little" impact (range of 100s of ms). On an absolute time scale, we
242 // don't provide stronger guarantees.
243 //
244 if (next.DueTime - next.Scheduler.Now >= RETRYSHORT)
245 {
246 ScheduleShortTermWork(next);
247 }
248 else
249 {
250 //
251 // Invocation happens on the recursive scheduler supplied to the function. We
252 // are already running on the target scheduler, so we should stay on board.
253 // Not doing so would have unexpected behavior for e.g. NewThreadScheduler,
254 // causing a whole new thread to be allocated because of a top-level call to
255 // the Schedule method rather than a recursive one.
256 //
257 // Notice if work got cancelled, the call to Invoke will not propagate to user
258 // code because of the IsDisposed check inside.
259 //
260 next.Invoke(scheduler);
261 }
262 }
263
264 //
265 // No need to return anything better here. We already handed out the original WorkItem
266 // object upon the call to Enqueue (called itself by Schedule). The disposable inside
267 // the work item allows a cancellation request to chase the underlying computation.
268 //
269 return Disposable.Empty;
270 }
271
272 /// <summary>
273 /// Schedule work that's due on the long term. This leads to the work being queued up for
274 /// eventual transitioning to the short term work list.
275 /// </summary>
276 /// <param name="item">Work item to schedule on the long term. The caller is responsible to determine the work is indeed long term.</param>
277 private static void ScheduleLongTermWork(WorkItem/*!*/ item)
278 {
279 lock (s_gate)
280 {
281 s_longTerm.Enqueue(item);
282
283 //
284 // In case we're the first long-term item in the queue now, the timer will have
285 // to be updated.
286 //
287 UpdateLongTermProcessingTimer();
288 }
289 }
290
291 /// <summary>
292 /// Updates the long term timer which is responsible to transition work from the head of the
293 /// long term queue to the short term work list.
294 /// </summary>
295 /// <remarks>Should be called under the scheduler lock.</remarks>
296 private static void UpdateLongTermProcessingTimer()
297 {
298 /*
299 * CALLERS - Ensure this is called under the lock!
300 *
301 lock (s_gate) */
302 {
303 if (s_longTerm.Count == 0)
304 return;
305
306 //
307 // To avoid setting the timer all over again for the first work item if it hasn't changed,
308 // we keep track of the next long term work item that will be processed by the timer.
309 //
310 var next = s_longTerm.Peek();
311 if (next == s_nextLongTermWorkItem)
312 return;
313
314 //
315 // We need to arrive early in order to accommodate for potential drift. The relative amount
316 // of drift correction is kept in MAXERRORRATIO. At the very least, we want to be LONGTOSHORT
317 // early to make the final jump from long term to short term, giving the target scheduler
318 // enough time to process the item through its queue. LONGTOSHORT is chosen such that the
319 // error due to drift is negligible.
320 //
321 var due = Scheduler.Normalize(next.DueTime - next.Scheduler.Now);
322 var remainder = TimeSpan.FromTicks(Math.Max(due.Ticks / MAXERRORRATIO, LONGTOSHORT.Ticks));
323 var dueEarly = due - remainder;
324
325 //
326 // Limit the interval to maximum supported by underlying Timer.
327 //
328 var dueCapped = TimeSpan.FromTicks(Math.Min(dueEarly.Ticks, MAXSUPPORTEDTIMER.Ticks));
329
330 s_nextLongTermWorkItem = next;
331 s_nextLongTermTimer.Disposable = ConcurrencyAbstractionLayer.Current.StartTimer(EvaluateLongTermQueue, null, dueCapped);
332 }
333 }
334
335 /// <summary>
336 /// Evaluates the long term queue, transitioning short term work to the short term list,
337 /// and adjusting the new long term processing timer accordingly.
338 /// </summary>
339 /// <param name="state">Ignored.</param>
340 private static void EvaluateLongTermQueue(object state)
341 {
342 lock (s_gate)
343 {
344 var next = default(WorkItem);
345
346 while (s_longTerm.Count > 0)
347 {
348 next = s_longTerm.Peek();
349
350 var due = Scheduler.Normalize(next.DueTime - next.Scheduler.Now);
351 if (due >= SHORTTERM)
352 break;
353
354 var item = s_longTerm.Dequeue();
355 ScheduleShortTermWork(item);
356 }
357
358 s_nextLongTermWorkItem = null;
359 UpdateLongTermProcessingTimer();
360 }
361 }
362
363 /// <summary>
364 /// Callback invoked when a system clock change is observed in order to adjust and reevaluate
365 /// the internal scheduling queues.
366 /// </summary>
367 /// <param name="args">Currently not used.</param>
368 /// <param name="sender">Currently not used.</param>
369 private static void SystemClockChanged(object sender, SystemClockChangedEventArgs args)
370 {
371 lock (s_gate)
372 {
373 //
374 // Best-effort cancellation of short term work. A check for presence in the hash set
375 // is used to notice race conditions between cancellation and the timer firing (also
376 // guarded by the same gate object). See checks in ExecuteNextShortTermWorkItem.
377 //
378 #if !NO_HASHSET
379 foreach (var d in s_shortTermWork)
380 #else
381 foreach (var d in s_shortTermWork.Keys)
382 #endif
383 d.Dispose();
384
385 s_shortTermWork.Clear();
386
387 //
388 // Transition short term work to the long term queue for reevaluation by calling the
389 // EvaluateLongTermQueue method. We don't know which direction the clock was changed
390 // in, so we don't optimize for special cases, but always transition the whole queue.
391 // Notice the short term queue is bounded to SHORTTERM length.
392 //
393 while (s_shortTerm.Count > 0)
394 {
395 var next = s_shortTerm.Dequeue();
396 s_longTerm.Enqueue(next);
397 }
398
399 //
400 // Reevaluate the queue and don't forget to null out the current timer to force the
401 // method to create a new timer for the new first long term item.
402 //
403 s_nextLongTermWorkItem = null;
404 EvaluateLongTermQueue(null);
405 }
406 }
407
408 /// <summary>
409 /// Represents a work item in the absolute time scheduler.
410 /// </summary>
411 /// <remarks>
412 /// This type is very similar to ScheduledItem, but we need a different Invoke signature to allow customization
413 /// of the target scheduler (e.g. when called in a recursive scheduling context, see ExecuteNextShortTermWorkItem).
414 /// </remarks>
415 abstract class WorkItem : IComparable<WorkItem>, IDisposable
416 {
417 private readonly IScheduler _scheduler;
418 private readonly DateTimeOffset _dueTime;
419 private readonly SingleAssignmentDisposable _disposable;
420 private int _hasRun;
421
422 public WorkItem(IScheduler scheduler, DateTimeOffset dueTime)
423 {
424 _scheduler = scheduler;
425 _dueTime = dueTime;
426 _disposable = new SingleAssignmentDisposable();
427 _hasRun = 0;
428 }
429
430 public IScheduler Scheduler
431 {
432 get { return _scheduler; }
433 }
434
435 public DateTimeOffset DueTime
436 {
437 get { return _dueTime; }
438 }
439
440 public void Invoke(IScheduler scheduler)
441 {
442 //
443 // Protect against possible maltreatment of the scheduler queues or races in
444 // execution of a work item that got relocated across system clock changes.
445 // Under no circumstance whatsoever we should run work twice. The monitor's
446 // ref count should also be subject to this policy.
447 //
448 if (Interlocked.Exchange(ref _hasRun, 1) == 0)
449 {
450 try
451 {
452 if (!_disposable.IsDisposed)
453 _disposable.Disposable = InvokeCore(scheduler);
454 }
455 finally
456 {
457 SystemClock.Release();
458 }
459 }
460 }
461
462 protected abstract IDisposable InvokeCore(IScheduler scheduler);
463
464 public int CompareTo(WorkItem/*!*/ other)
465 {
466 return Comparer<DateTimeOffset>.Default.Compare(this._dueTime, other._dueTime);
467 }
468
469 public void Dispose()
470 {
471 _disposable.Dispose();
472 }
473 }
474
475 /// <summary>
476 /// Represents a work item that closes over scheduler invocation state. Subtyping is
477 /// used to have a common type for the scheduler queues.
478 /// </summary>
479 sealed class WorkItem<TState> : WorkItem
480 {
481 private readonly TState _state;
482 private readonly Func<IScheduler, TState, IDisposable> _action;
483
484 public WorkItem(IScheduler scheduler, TState state, DateTimeOffset dueTime, Func<IScheduler, TState, IDisposable> action)
485 : base(scheduler, dueTime)
486 {
487 _state = state;
488 _action = action;
489 }
490
491 protected override IDisposable InvokeCore(IScheduler scheduler)
492 {
493 return _action(scheduler, _state);
494 }
495 }
496 }
497 }