LocalScheduler.TimerQueue.cs 23 KB

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