123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829 |
- // Licensed to the .NET Foundation under one or more agreements.
- // The .NET Foundation licenses this file to you under the MIT License.
- // See the LICENSE file in the project root for more information.
- using System.Collections.Generic;
- using System.Reactive.Concurrency;
- using System.Reactive.Disposables;
- using System.Threading;
- namespace System.Reactive.Linq.ObservableImpl
- {
- internal static class Delay<TSource>
- {
- internal abstract class Base<TParent> : Producer<TSource, Base<TParent>._>
- where TParent : Base<TParent>
- {
- protected readonly IObservable<TSource> _source;
- protected readonly IScheduler _scheduler;
- protected Base(IObservable<TSource> source, IScheduler scheduler)
- {
- _source = source;
- _scheduler = scheduler;
- }
- internal abstract class _ : IdentitySink<TSource>
- {
- protected readonly IScheduler _scheduler;
- private IStopwatch? _watch;
- protected _(TParent parent, IObserver<TSource> observer)
- : base(observer)
- {
- _scheduler = parent._scheduler;
- }
- public void Run(TParent parent)
- {
- _watch = _scheduler.StartStopwatch();
- RunCore(parent);
- base.Run(parent._source);
- }
- protected TimeSpan Elapsed => _watch!.Elapsed; // NB: Only used after Run is called.
- protected abstract void RunCore(TParent parent);
- }
- internal abstract class S : _
- {
- protected readonly object _gate = new object();
- protected SerialDisposableValue _cancelable;
- protected S(TParent parent, IObserver<TSource> observer)
- : base(parent, observer)
- {
- }
- protected TimeSpan _delay;
- protected bool _ready;
- protected bool _active;
- protected bool _running;
- protected Queue<Reactive.TimeInterval<TSource>> _queue = new Queue<Reactive.TimeInterval<TSource>>();
- private bool _hasCompleted;
- private TimeSpan _completeAt;
- private bool _hasFailed;
- private Exception? _exception;
- protected override void Dispose(bool disposing)
- {
- base.Dispose(disposing);
- if (disposing)
- {
- _cancelable.Dispose();
- }
- }
- public override void OnNext(TSource value)
- {
- var shouldRun = false;
- lock (_gate)
- {
- var next = Elapsed.Add(_delay);
- _queue.Enqueue(new Reactive.TimeInterval<TSource>(value, next));
- shouldRun = _ready && !_active;
- _active = true;
- }
- if (shouldRun)
- {
- DrainQueue(_delay);
- }
- }
- public override void OnError(Exception error)
- {
- DisposeUpstream();
- var shouldRun = false;
- lock (_gate)
- {
- _queue.Clear();
- _exception = error;
- _hasFailed = true;
- shouldRun = !_running;
- }
- if (shouldRun)
- {
- ForwardOnError(error);
- }
- }
- public override void OnCompleted()
- {
- DisposeUpstream();
- var shouldRun = false;
- lock (_gate)
- {
- var next = Elapsed.Add(_delay);
- _completeAt = next;
- _hasCompleted = true;
- shouldRun = _ready && !_active;
- _active = true;
- }
- if (shouldRun)
- {
- DrainQueue(_delay);
- }
- }
- protected void DrainQueue(TimeSpan next)
- {
- _cancelable.Disposable = _scheduler.Schedule(this, next, static (@this, a) => @this.DrainQueue(a));
- }
- private void DrainQueue(Action<S, TimeSpan> recurse)
- {
- lock (_gate)
- {
- if (_hasFailed)
- {
- return;
- }
- _running = true;
- }
- //
- // The shouldYield flag was added to address TFS 487881: "Delay can be unfair". In the old
- // implementation, the loop below kept running while there was work for immediate dispatch,
- // potentially causing a long running work item on the target scheduler. With the addition
- // of long-running scheduling in Rx v2.0, we can check whether the scheduler supports this
- // interface and perform different processing (see LongRunningImpl). To reduce the code
- // churn in the old loop code here, we set the shouldYield flag to true after the first
- // dispatch iteration, in order to break from the loop and enter the recursive scheduling path.
- //
- var shouldYield = false;
- while (true)
- {
- var hasFailed = false;
- var error = default(Exception);
- var hasValue = false;
- var value = default(TSource);
- var hasCompleted = false;
- var shouldRecurse = false;
- var recurseDueTime = default(TimeSpan);
- lock (_gate)
- {
- if (_hasFailed)
- {
- error = _exception;
- hasFailed = true;
- _running = false;
- }
- else
- {
- var now = Elapsed;
- if (_queue.Count > 0)
- {
- var nextDue = _queue.Peek().Interval;
- if (nextDue.CompareTo(now) <= 0 && !shouldYield)
- {
- value = _queue.Dequeue().Value;
- hasValue = true;
- }
- else
- {
- shouldRecurse = true;
- recurseDueTime = Scheduler.Normalize(nextDue.Subtract(now));
- _running = false;
- }
- }
- else if (_hasCompleted)
- {
- if (_completeAt.CompareTo(now) <= 0 && !shouldYield)
- {
- hasCompleted = true;
- }
- else
- {
- shouldRecurse = true;
- recurseDueTime = Scheduler.Normalize(_completeAt.Subtract(now));
- _running = false;
- }
- }
- else
- {
- _running = false;
- _active = false;
- }
- }
- } /* lock (_gate) */
- if (hasValue)
- {
- ForwardOnNext(value!);
- shouldYield = true;
- }
- else
- {
- if (hasCompleted)
- {
- ForwardOnCompleted();
- }
- else if (hasFailed)
- {
- ForwardOnError(error!);
- }
- else if (shouldRecurse)
- {
- recurse(this, recurseDueTime);
- }
- return;
- }
- } /* while (true) */
- }
- }
- protected abstract class L : _
- {
- protected readonly object _gate = new object();
- private readonly SemaphoreSlim _evt = new SemaphoreSlim(0);
- protected L(TParent parent, IObserver<TSource> observer)
- : base(parent, observer)
- {
- }
- protected Queue<Reactive.TimeInterval<TSource>> _queue = new Queue<Reactive.TimeInterval<TSource>>();
- protected SerialDisposableValue _cancelable;
- protected TimeSpan _delay;
- private bool _hasCompleted;
- private TimeSpan _completeAt;
- private bool _hasFailed;
- private Exception? _exception;
- protected override void Dispose(bool disposing)
- {
- base.Dispose(disposing);
- if (disposing)
- {
- _cancelable.Dispose();
- }
- }
- protected void ScheduleDrain()
- {
- var cd = new CancellationDisposable();
- _cancelable.Disposable = cd;
- _scheduler.AsLongRunning()!.ScheduleLongRunning(cd.Token, DrainQueue); // NB: This class is only used with long-running schedulers.
- }
- public override void OnNext(TSource value)
- {
- lock (_gate)
- {
- var next = Elapsed.Add(_delay);
- _queue.Enqueue(new Reactive.TimeInterval<TSource>(value, next));
- _evt.Release();
- }
- }
- public override void OnError(Exception error)
- {
- DisposeUpstream();
- lock (_gate)
- {
- _queue.Clear();
- _exception = error;
- _hasFailed = true;
- _evt.Release();
- }
- }
- public override void OnCompleted()
- {
- DisposeUpstream();
- lock (_gate)
- {
- var next = Elapsed.Add(_delay);
- _completeAt = next;
- _hasCompleted = true;
- _evt.Release();
- }
- }
- private void DrainQueue(CancellationToken token, ICancelable cancel)
- {
- while (true)
- {
- try
- {
- _evt.Wait(token);
- }
- catch (OperationCanceledException)
- {
- return;
- }
- var hasFailed = false;
- var error = default(Exception);
- var hasValue = false;
- var value = default(TSource);
- var hasCompleted = false;
- var shouldWait = false;
- var waitTime = default(TimeSpan);
- lock (_gate)
- {
- if (_hasFailed)
- {
- error = _exception;
- hasFailed = true;
- }
- else
- {
- var now = Elapsed;
- if (_queue.Count > 0)
- {
- var next = _queue.Dequeue();
- hasValue = true;
- value = next.Value;
- var nextDue = next.Interval;
- if (nextDue.CompareTo(now) > 0)
- {
- shouldWait = true;
- waitTime = Scheduler.Normalize(nextDue.Subtract(now));
- }
- }
- else if (_hasCompleted)
- {
- hasCompleted = true;
- if (_completeAt.CompareTo(now) > 0)
- {
- shouldWait = true;
- waitTime = Scheduler.Normalize(_completeAt.Subtract(now));
- }
- }
- }
- } /* lock (_gate) */
- if (shouldWait)
- {
- var timer = new ManualResetEventSlim();
- _scheduler.ScheduleAction(timer, waitTime, static slimTimer => { slimTimer.Set(); });
- try
- {
- timer.Wait(token);
- }
- catch (OperationCanceledException)
- {
- return;
- }
- }
- if (hasValue)
- {
- ForwardOnNext(value!);
- }
- else
- {
- if (hasCompleted)
- {
- ForwardOnCompleted();
- }
- else if (hasFailed)
- {
- ForwardOnError(error!);
- }
- return;
- }
- }
- }
- }
- }
- internal sealed class Absolute : Base<Absolute>
- {
- private readonly DateTimeOffset _dueTime;
- public Absolute(IObservable<TSource> source, DateTimeOffset dueTime, IScheduler scheduler)
- : base(source, scheduler)
- {
- _dueTime = dueTime;
- }
- protected override _ CreateSink(IObserver<TSource> observer) => _scheduler.AsLongRunning() != null ? (_)new L(this, observer) : new S(this, observer);
- protected override void Run(_ sink) => sink.Run(this);
- private new sealed class S : Base<Absolute>.S
- {
- public S(Absolute parent, IObserver<TSource> observer)
- : base(parent, observer)
- {
- }
- protected override void RunCore(Absolute parent)
- {
- _ready = false;
- _cancelable.TrySetFirst(parent._scheduler.ScheduleAction(this, parent._dueTime, static @this => @this.Start()));
- }
- private void Start()
- {
- var next = default(TimeSpan);
- var shouldRun = false;
- lock (_gate)
- {
- _delay = Elapsed;
- var oldQueue = _queue;
- _queue = new Queue<Reactive.TimeInterval<TSource>>();
- if (oldQueue.Count > 0)
- {
- next = oldQueue.Peek().Interval;
- while (oldQueue.Count > 0)
- {
- var item = oldQueue.Dequeue();
- _queue.Enqueue(new Reactive.TimeInterval<TSource>(item.Value, item.Interval.Add(_delay)));
- }
- shouldRun = true;
- _active = true;
- }
- _ready = true;
- }
- if (shouldRun)
- {
- DrainQueue(next);
- }
- }
- }
- private new sealed class L : Base<Absolute>.L
- {
- public L(Absolute parent, IObserver<TSource> observer)
- : base(parent, observer)
- {
- }
- protected override void RunCore(Absolute parent)
- {
- // ScheduleDrain might have already set a newer disposable
- // using TrySetSerial would cancel it, stopping the emission
- // and hang the consumer
- _cancelable.TrySetFirst(parent._scheduler.ScheduleAction(this, parent._dueTime, static @this => @this.Start()));
- }
- private void Start()
- {
- lock (_gate)
- {
- _delay = Elapsed;
- var oldQueue = _queue;
- _queue = new Queue<Reactive.TimeInterval<TSource>>();
- while (oldQueue.Count > 0)
- {
- var item = oldQueue.Dequeue();
- _queue.Enqueue(new Reactive.TimeInterval<TSource>(item.Value, item.Interval.Add(_delay)));
- }
- }
- ScheduleDrain();
- }
- }
- }
- internal sealed class Relative : Base<Relative>
- {
- private readonly TimeSpan _dueTime;
- public Relative(IObservable<TSource> source, TimeSpan dueTime, IScheduler scheduler)
- : base(source, scheduler)
- {
- _dueTime = dueTime;
- }
- protected override _ CreateSink(IObserver<TSource> observer) => _scheduler.AsLongRunning() != null ? (_)new L(this, observer) : new S(this, observer);
- protected override void Run(_ sink) => sink.Run(this);
- private new sealed class S : Base<Relative>.S
- {
- public S(Relative parent, IObserver<TSource> observer)
- : base(parent, observer)
- {
- }
- protected override void RunCore(Relative parent)
- {
- _ready = true;
- _delay = Scheduler.Normalize(parent._dueTime);
- }
- }
- private new sealed class L : Base<Relative>.L
- {
- public L(Relative parent, IObserver<TSource> observer)
- : base(parent, observer)
- {
- }
- protected override void RunCore(Relative parent)
- {
- _delay = Scheduler.Normalize(parent._dueTime);
- ScheduleDrain();
- }
- }
- }
- }
- internal static class Delay<TSource, TDelay>
- {
- internal abstract class Base<TParent> : Producer<TSource, Base<TParent>._>
- where TParent : Base<TParent>
- {
- protected readonly IObservable<TSource> _source;
- protected Base(IObservable<TSource> source)
- {
- _source = source;
- }
- internal abstract class _ : IdentitySink<TSource>
- {
- private readonly CompositeDisposable _delays = new CompositeDisposable();
- private readonly object _gate = new object();
- private readonly Func<TSource, IObservable<TDelay>> _delaySelector;
- protected _(Func<TSource, IObservable<TDelay>> delaySelector, IObserver<TSource> observer)
- : base(observer)
- {
- _delaySelector = delaySelector;
- }
- private bool _atEnd;
- private SingleAssignmentDisposableValue _subscription;
- public void Run(TParent parent)
- {
- _atEnd = false;
- _subscription.Disposable = RunCore(parent);
- }
- protected override void Dispose(bool disposing)
- {
- if (disposing)
- {
- _subscription.Dispose();
- _delays.Dispose();
- }
- base.Dispose(disposing);
- }
- protected abstract IDisposable RunCore(TParent parent);
- public override void OnNext(TSource value)
- {
- IObservable<TDelay> delay;
- try
- {
- delay = _delaySelector(value);
- }
- catch (Exception error)
- {
- lock (_gate)
- {
- ForwardOnError(error);
- }
- return;
- }
- var observer = new DelayObserver(this, value);
- _delays.Add(observer);
- observer.SetResource(delay.SubscribeSafe(observer));
- }
- public override void OnError(Exception error)
- {
- lock (_gate)
- {
- ForwardOnError(error);
- }
- }
- public override void OnCompleted()
- {
- lock (_gate)
- {
- _atEnd = true;
- _subscription.Dispose();
- CheckDone();
- }
- }
- private void CheckDone()
- {
- if (_atEnd && _delays.Count == 0)
- {
- ForwardOnCompleted();
- }
- }
- private sealed class DelayObserver : SafeObserver<TDelay>
- {
- private readonly _ _parent;
- private readonly TSource _value;
- private bool _once;
- public DelayObserver(_ parent, TSource value)
- {
- _parent = parent;
- _value = value;
- }
- public override void OnNext(TDelay value)
- {
- if (!_once)
- {
- _once = true;
- lock (_parent._gate)
- {
- _parent.ForwardOnNext(_value);
- _parent._delays.Remove(this);
- _parent.CheckDone();
- }
- }
- }
- public override void OnError(Exception error)
- {
- lock (_parent._gate)
- {
- _parent.ForwardOnError(error);
- }
- }
- public override void OnCompleted()
- {
- if (!_once)
- {
- lock (_parent._gate)
- {
- _parent.ForwardOnNext(_value);
- _parent._delays.Remove(this);
- _parent.CheckDone();
- }
- }
- }
- }
- }
- }
- internal class Selector : Base<Selector>
- {
- private readonly Func<TSource, IObservable<TDelay>> _delaySelector;
- public Selector(IObservable<TSource> source, Func<TSource, IObservable<TDelay>> delaySelector)
- : base(source)
- {
- _delaySelector = delaySelector;
- }
- protected override Base<Selector>._ CreateSink(IObserver<TSource> observer) => new _(_delaySelector, observer);
- protected override void Run(Base<Selector>._ sink) => sink.Run(this);
- private new sealed class _ : Base<Selector>._
- {
- public _(Func<TSource, IObservable<TDelay>> delaySelector, IObserver<TSource> observer)
- : base(delaySelector, observer)
- {
- }
- protected override IDisposable RunCore(Selector parent) => parent._source.SubscribeSafe(this);
- }
- }
- internal sealed class SelectorWithSubscriptionDelay : Base<SelectorWithSubscriptionDelay>
- {
- private readonly IObservable<TDelay> _subscriptionDelay;
- private readonly Func<TSource, IObservable<TDelay>> _delaySelector;
- public SelectorWithSubscriptionDelay(IObservable<TSource> source, IObservable<TDelay> subscriptionDelay, Func<TSource, IObservable<TDelay>> delaySelector)
- : base(source)
- {
- _subscriptionDelay = subscriptionDelay;
- _delaySelector = delaySelector;
- }
- protected override Base<SelectorWithSubscriptionDelay>._ CreateSink(IObserver<TSource> observer) => new _(_delaySelector, observer);
- protected override void Run(Base<SelectorWithSubscriptionDelay>._ sink) => sink.Run(this);
- private new sealed class _ : Base<SelectorWithSubscriptionDelay>._
- {
- public _(Func<TSource, IObservable<TDelay>> delaySelector, IObserver<TSource> observer)
- : base(delaySelector, observer)
- {
- }
- protected override IDisposable RunCore(SelectorWithSubscriptionDelay parent)
- {
- var delayConsumer = new SubscriptionDelayObserver(this, parent._source);
- delayConsumer.SetFirst(parent._subscriptionDelay.SubscribeSafe(delayConsumer));
- return delayConsumer;
- }
- private sealed class SubscriptionDelayObserver : IObserver<TDelay>, IDisposable
- {
- private readonly _ _parent;
- private readonly IObservable<TSource> _source;
- private SerialDisposableValue _subscription;
- public SubscriptionDelayObserver(_ parent, IObservable<TSource> source)
- {
- _parent = parent;
- _source = source;
- }
- internal void SetFirst(IDisposable d)
- {
- _subscription.TrySetFirst(d);
- }
- public void OnNext(TDelay value)
- {
- _subscription.Disposable = _source.SubscribeSafe(_parent);
- }
- public void OnError(Exception error)
- {
- _parent.ForwardOnError(error);
- }
- public void OnCompleted()
- {
- _subscription.Disposable = _source.SubscribeSafe(_parent);
- }
- public void Dispose()
- {
- _subscription.Dispose();
- }
- }
- }
- }
- }
- }
|