Timer.cs 13 KB

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