1
0

Timer.cs 11 KB

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