1
0

Timer.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. #if !NO_PERF
  3. using System;
  4. using System.Diagnostics;
  5. using System.Reactive.Concurrency;
  6. using System.Reactive.Disposables;
  7. using System.Threading;
  8. namespace System.Reactive.Linq.ObservableImpl
  9. {
  10. class Timer : Producer<long>
  11. {
  12. private readonly DateTimeOffset? _dueTimeA;
  13. private readonly TimeSpan? _dueTimeR;
  14. private readonly TimeSpan? _period;
  15. private readonly IScheduler _scheduler;
  16. public Timer(DateTimeOffset dueTime, TimeSpan? period, IScheduler scheduler)
  17. {
  18. _dueTimeA = dueTime;
  19. _period = period;
  20. _scheduler = scheduler;
  21. }
  22. public Timer(TimeSpan dueTime, TimeSpan? period, IScheduler scheduler)
  23. {
  24. _dueTimeR = dueTime;
  25. _period = period;
  26. _scheduler = scheduler;
  27. }
  28. protected override IDisposable Run(IObserver<long> observer, IDisposable cancel, Action<IDisposable> setSink)
  29. {
  30. if (_period.HasValue)
  31. {
  32. var sink = new TimerImpl(this, observer, cancel);
  33. setSink(sink);
  34. return sink.Run();
  35. }
  36. else
  37. {
  38. var sink = new _(this, observer, cancel);
  39. setSink(sink);
  40. return sink.Run();
  41. }
  42. }
  43. class _ : Sink<long>
  44. {
  45. private readonly Timer _parent;
  46. public _(Timer parent, IObserver<long> observer, IDisposable cancel)
  47. : base(observer, cancel)
  48. {
  49. _parent = parent;
  50. }
  51. public IDisposable Run()
  52. {
  53. if (_parent._dueTimeA.HasValue)
  54. {
  55. return _parent._scheduler.Schedule(_parent._dueTimeA.Value, Invoke);
  56. }
  57. else
  58. {
  59. return _parent._scheduler.Schedule(_parent._dueTimeR.Value, Invoke);
  60. }
  61. }
  62. private void Invoke()
  63. {
  64. base._observer.OnNext(0);
  65. base._observer.OnCompleted();
  66. base.Dispose();
  67. }
  68. }
  69. class TimerImpl : Sink<long>
  70. {
  71. private readonly Timer _parent;
  72. private readonly TimeSpan _period;
  73. public TimerImpl(Timer parent, IObserver<long> observer, IDisposable cancel)
  74. : base(observer, cancel)
  75. {
  76. _parent = parent;
  77. _period = _parent._period.Value;
  78. }
  79. public IDisposable Run()
  80. {
  81. if (_parent._dueTimeA.HasValue)
  82. {
  83. var dueTime = _parent._dueTimeA.Value;
  84. return _parent._scheduler.Schedule(default(object), dueTime, InvokeStart);
  85. }
  86. else
  87. {
  88. var dueTime = _parent._dueTimeR.Value;
  89. //
  90. // Optimize for the case of Observable.Interval.
  91. //
  92. if (dueTime == _period)
  93. {
  94. return _parent._scheduler.SchedulePeriodic(0L, _period, (Func<long, long>)Tick);
  95. }
  96. return _parent._scheduler.Schedule(default(object), dueTime, InvokeStart);
  97. }
  98. }
  99. //
  100. // BREAKING CHANGE v2 > v1.x - No more correction for time drift based on absolute time. This
  101. // didn't work for large period values anyway; the fractional
  102. // error exceeded corrections. Also complicated dealing with system
  103. // clock change conditions and caused numerous bugs.
  104. //
  105. // - For more precise scheduling, use a custom scheduler that measures TimeSpan values in a
  106. // better way, e.g. spinning to make up for the last part of the period. Whether or not the
  107. // values of the TimeSpan period match NT time or wall clock time is up to the scheduler.
  108. //
  109. // - For more accurate scheduling wrt the system clock, use Generate with DateTimeOffset time
  110. // selectors. When the system clock changes, intervals will not be the same as diffs between
  111. // consecutive absolute time values. The precision will be low (1s range by default).
  112. //
  113. private long Tick(long count)
  114. {
  115. base._observer.OnNext(count);
  116. return unchecked(count + 1);
  117. }
  118. private int _pendingTickCount;
  119. private IDisposable _periodic;
  120. private IDisposable InvokeStart(IScheduler self, object state)
  121. {
  122. //
  123. // Notice the first call to OnNext will introduce skew if it takes significantly long when
  124. // using the following naive implementation:
  125. //
  126. // Code: base._observer.OnNext(0L);
  127. // return self.SchedulePeriodicEmulated(1L, _period, (Func<long, long>)Tick);
  128. //
  129. // What we're saying here is that Observable.Timer(dueTime, period) is pretty much the same
  130. // as writing Observable.Timer(dueTime).Concat(Observable.Interval(period)).
  131. //
  132. // Expected: dueTime
  133. // |
  134. // 0--period--1--period--2--period--3--period--4--...
  135. // |
  136. // +-OnNext(0L)-|
  137. //
  138. // Actual: dueTime
  139. // |
  140. // 0------------#--period--1--period--2--period--3--period--4--...
  141. // |
  142. // +-OnNext(0L)-|
  143. //
  144. // Different solutions for this behavior have different problems:
  145. //
  146. // 1. Scheduling the periodic job first and using an AsyncLock to serialize the OnNext calls
  147. // has the drawback that InvokeStart may never return. This happens when every callback
  148. // doesn't meet the period's deadline, hence the periodic job keeps queueing stuff up. In
  149. // this case, InvokeStart stays the owner of the AsyncLock and the call to Wait will never
  150. // return, thus not allowing any interleaving of work on this scheduler's logical thread.
  151. //
  152. // 2. Scheduling the periodic job first and using a (blocking) synchronization primitive to
  153. // signal completion of the OnNext(0L) call to the Tick call requires quite a bit of state
  154. // and careful handling of the case when OnNext(0L) throws. What's worse is the blocking
  155. // behavior inside Tick.
  156. //
  157. // In order to avoid blocking behavior, we need a scheme much like SchedulePeriodic emulation
  158. // where work to dispatch OnNext(n + 1) is delegated to a catch up loop in case OnNext(n) was
  159. // still running. Because SchedulePeriodic emulation exhibits such behavior in all cases, we
  160. // only need to deal with the overlap of OnNext(0L) with future periodic OnNext(n) dispatch
  161. // jobs. In the worst case where every callback takes longer than the deadline implied by the
  162. // period, the periodic job will just queue up work that's dispatched by the tail-recursive
  163. // catch up loop. In the best case, all work will be dispatched on the periodic scheduler.
  164. //
  165. //
  166. // We start with one tick pending because we're about to start doing OnNext(0L).
  167. //
  168. _pendingTickCount = 1;
  169. var d = new SingleAssignmentDisposable();
  170. _periodic = d;
  171. d.Disposable = self.SchedulePeriodic(1L, _period, (Func<long, long>)Tock);
  172. try
  173. {
  174. base._observer.OnNext(0L);
  175. }
  176. catch (Exception e)
  177. {
  178. d.Dispose();
  179. e.Throw();
  180. }
  181. //
  182. // If the periodic scheduling job already ran before we finished dispatching the OnNext(0L)
  183. // call, we'll find pendingTickCount to be > 1. In this case, we need to catch up by dispatching
  184. // subsequent calls to OnNext as fast as possible, but without running a loop in order to ensure
  185. // fair play with the scheduler. So, we run a tail-recursive loop in CatchUp instead.
  186. //
  187. if (Interlocked.Decrement(ref _pendingTickCount) > 0)
  188. {
  189. var c = new SingleAssignmentDisposable();
  190. c.Disposable = self.Schedule(1L, CatchUp);
  191. return StableCompositeDisposable.Create(d, c);
  192. }
  193. return d;
  194. }
  195. private long Tock(long count)
  196. {
  197. //
  198. // Notice the handler for (emulated) periodic scheduling is non-reentrant.
  199. //
  200. // When there's no overlap with the OnNext(0L) call, the following code will cycle through
  201. // pendingTickCount 0 -> 1 -> 0 for the remainder of the timer's execution.
  202. //
  203. // If there's overlap with the OnNext(0L) call, pendingTickCount will increase to record
  204. // the number of catch up OnNext calls required, which will be dispatched by the recursive
  205. // scheduling loop in CatchUp (which quits when it reaches 0 pending ticks).
  206. //
  207. if (Interlocked.Increment(ref _pendingTickCount) == 1)
  208. {
  209. base._observer.OnNext(count);
  210. Interlocked.Decrement(ref _pendingTickCount);
  211. }
  212. return unchecked(count + 1);
  213. }
  214. private void CatchUp(long count, Action<long> recurse)
  215. {
  216. try
  217. {
  218. base._observer.OnNext(count);
  219. }
  220. catch (Exception e)
  221. {
  222. _periodic.Dispose();
  223. e.Throw();
  224. }
  225. //
  226. // We can simply bail out if we decreased the tick count to 0. In that case, the Tock
  227. // method will take over when it sees the 0 -> 1 transition.
  228. //
  229. if (Interlocked.Decrement(ref _pendingTickCount) > 0)
  230. {
  231. recurse(unchecked(count + 1));
  232. }
  233. }
  234. }
  235. }
  236. }
  237. #endif