Timer.cs 11 KB

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