| 1 |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. |
| 2 |
|
| 3 |
#if !NO_PERF |
| 4 |
using System; |
| 5 |
using System.Diagnostics; |
| 6 |
using System.Reactive.Concurrency; |
| 7 |
using System.Reactive.Disposables; |
| 8 |
using System.Threading; |
| 9 |
|
| 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 |
|
| 19 |
public Timer(DateTimeOffset dueTime, TimeSpan? period, IScheduler scheduler) |
| 20 |
{ |
| 21 |
_dueTimeA = dueTime; |
| 22 |
_period = period; |
| 23 |
_scheduler = scheduler; |
| 24 |
} |
| 25 |
|
| 26 |
public Timer(TimeSpan dueTime, TimeSpan? period, IScheduler scheduler) |
| 27 |
{ |
| 28 |
_dueTimeR = dueTime; |
| 29 |
_period = period; |
| 30 |
_scheduler = scheduler; |
| 31 |
} |
| 32 |
|
| 33 |
protected override IDisposable Run(IObserver<long> observer, IDisposable cancel, Action<IDisposable> setSink) |
| 34 |
{ |
| 35 |
if (_period.HasValue) |
| 36 |
{ |
| 37 |
var sink = new TimerImpl(this, observer, cancel); |
| 38 |
setSink(sink); |
| 39 |
return sink.Run(); |
| 40 |
} |
| 41 |
else |
| 42 |
{ |
| 43 |
var sink = new _(this, observer, cancel); |
| 44 |
setSink(sink); |
| 45 |
return sink.Run(); |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
class _ : Sink<long> |
| 50 |
{ |
| 51 |
private readonly Timer _parent; |
| 52 |
|
| 53 |
public _(Timer parent, IObserver<long> observer, IDisposable cancel) |
| 54 |
: base(observer, cancel) |
| 55 |
{ |
| 56 |
_parent = parent; |
| 57 |
} |
| 58 |
|
| 59 |
public IDisposable Run() |
| 60 |
{ |
| 61 |
if (_parent._dueTimeA.HasValue) |
| 62 |
{ |
| 63 |
return _parent._scheduler.Schedule(_parent._dueTimeA.Value, Invoke); |
| 64 |
} |
| 65 |
else |
| 66 |
{ |
| 67 |
return _parent._scheduler.Schedule(_parent._dueTimeR.Value, Invoke); |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
private void Invoke() |
| 72 |
{ |
| 73 |
base._observer.OnNext(0); |
| 74 |
base._observer.OnCompleted(); |
| 75 |
base.Dispose(); |
| 76 |
} |
| 77 |
} |
| 78 |
|
| 79 |
class TimerImpl : Sink<long> |
| 80 |
{ |
| 81 |
private readonly Timer _parent; |
| 82 |
private readonly TimeSpan _period; |
| 83 |
|
| 84 |
public TimerImpl(Timer parent, IObserver<long> observer, IDisposable cancel) |
| 85 |
: base(observer, cancel) |
| 86 |
{ |
| 87 |
_parent = parent; |
| 88 |
_period = _parent._period.Value; |
| 89 |
} |
| 90 |
|
| 91 |
public IDisposable Run() |
| 92 |
{ |
| 93 |
if (_parent._dueTimeA.HasValue) |
| 94 |
{ |
| 95 |
var dueTime = _parent._dueTimeA.Value; |
| 96 |
return _parent._scheduler.Schedule(default(object), dueTime, InvokeStart); |
| 97 |
} |
| 98 |
else |
| 99 |
{ |
| 100 |
var dueTime = _parent._dueTimeR.Value; |
| 101 |
|
| 102 |
// |
| 103 |
// Optimize for the case of Observable.Interval. |
| 104 |
// |
| 105 |
if (dueTime == _period) |
| 106 |
{ |
| 107 |
return _parent._scheduler.SchedulePeriodic(0L, _period, (Func<long, long>)Tick); |
| 108 |
} |
| 109 |
|
| 110 |
return _parent._scheduler.Schedule(default(object), dueTime, InvokeStart); |
| 111 |
} |
| 112 |
} |
| 113 |
|
| 114 |
// |
| 115 |
// BREAKING CHANGE v2 > v1.x - No more correction for time drift based on absolute time. This |
| 116 |
// didn't work for large period values anyway; the fractional |
| 117 |
// error exceeded corrections. Also complicated dealing with system |
| 118 |
// clock change conditions and caused numerous bugs. |
| 119 |
// |
| 120 |
// - For more precise scheduling, use a custom scheduler that measures TimeSpan values in a |
| 121 |
// better way, e.g. spinning to make up for the last part of the period. Whether or not the |
| 122 |
// values of the TimeSpan period match NT time or wall clock time is up to the scheduler. |
| 123 |
// |
| 124 |
// - For more accurate scheduling wrt the system clock, use Generate with DateTimeOffset time |
| 125 |
// selectors. When the system clock changes, intervals will not be the same as diffs between |
| 126 |
// consecutive absolute time values. The precision will be low (1s range by default). |
| 127 |
// |
| 128 |
private long Tick(long count) |
| 129 |
{ |
| 130 |
base._observer.OnNext(count); |
| 131 |
return unchecked(count + 1); |
| 132 |
} |
| 133 |
|
| 134 |
private int _pendingTickCount; |
| 135 |
private IDisposable _periodic; |
| 136 |
|
| 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 |
// |
| 184 |
// We start with one tick pending because we're about to start doing OnNext(0L). |
| 185 |
// |
| 186 |
_pendingTickCount = 1; |
| 187 |
|
| 188 |
var d = new SingleAssignmentDisposable(); |
| 189 |
_periodic = d; |
| 190 |
d.Disposable = self.SchedulePeriodic(1L, _period, (Func<long, long>)Tock); |
| 191 |
|
| 192 |
try |
| 193 |
{ |
| 194 |
base._observer.OnNext(0L); |
| 195 |
} |
| 196 |
catch (Exception e) |
| 197 |
{ |
| 198 |
d.Dispose(); |
| 199 |
e.Throw(); |
| 200 |
} |
| 201 |
|
| 202 |
// |
| 203 |
// If the periodic scheduling job already ran before we finished dispatching the OnNext(0L) |
| 204 |
// call, we'll find pendingTickCount to be > 1. In this case, we need to catch up by dispatching |
| 205 |
// subsequent calls to OnNext as fast as possible, but without running a loop in order to ensure |
| 206 |
// fair play with the scheduler. So, we run a tail-recursive loop in CatchUp instead. |
| 207 |
// |
| 208 |
if (Interlocked.Decrement(ref _pendingTickCount) > 0) |
| 209 |
{ |
| 210 |
var c = new SingleAssignmentDisposable(); |
| 211 |
c.Disposable = self.Schedule(1L, CatchUp); |
| 212 |
|
| 213 |
return new CompositeDisposable(2) { d, c }; |
| 214 |
} |
| 215 |
|
| 216 |
return d; |
| 217 |
} |
| 218 |
|
| 219 |
private long Tock(long count) |
| 220 |
{ |
| 221 |
// |
| 222 |
// Notice the handler for (emulated) periodic scheduling is non-reentrant. |
| 223 |
// |
| 224 |
// When there's no overlap with the OnNext(0L) call, the following code will cycle through |
| 225 |
// pendingTickCount 0 -> 1 -> 0 for the remainder of the timer's execution. |
| 226 |
// |
| 227 |
// If there's overlap with the OnNext(0L) call, pendingTickCount will increase to record |
| 228 |
// the number of catch up OnNext calls required, which will be dispatched by the recursive |
| 229 |
// scheduling loop in CatchUp (which quits when it reaches 0 pending ticks). |
| 230 |
// |
| 231 |
if (Interlocked.Increment(ref _pendingTickCount) == 1) |
| 232 |
{ |
| 233 |
base._observer.OnNext(count); |
| 234 |
Interlocked.Decrement(ref _pendingTickCount); |
| 235 |
} |
| 236 |
|
| 237 |
return unchecked(count + 1); |
| 238 |
} |
| 239 |
|
| 240 |
private void CatchUp(long count, Action<long> recurse) |
| 241 |
{ |
| 242 |
try |
| 243 |
{ |
| 244 |
base._observer.OnNext(count); |
| 245 |
} |
| 246 |
catch (Exception e) |
| 247 |
{ |
| 248 |
_periodic.Dispose(); |
| 249 |
e.Throw(); |
| 250 |
} |
| 251 |
|
| 252 |
// |
| 253 |
// We can simply bail out if we decreased the tick count to 0. In that case, the Tock |
| 254 |
// method will take over when it sees the 0 -> 1 transition. |
| 255 |
// |
| 256 |
if (Interlocked.Decrement(ref _pendingTickCount) > 0) |
| 257 |
{ |
| 258 |
recurse(unchecked(count + 1)); |
| 259 |
} |
| 260 |
} |
| 261 |
} |
| 262 |
} |
| 263 |
} |
| 264 |
#endif |