Debian Codegraph @

external/rx/Rx/NET/Source/System.Reactive.Core/Reactive/Internal/ScheduledObserver.cs

raw
1 // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
2
3 using System.Collections.Generic;
4 using System.Reactive.Concurrency;
5 using System.Reactive.Disposables;
6 using System.Threading;
7
8 namespace System.Reactive
9 {
10 #if !NO_PERF && !NO_CDS
11 using System.Collections.Concurrent;
12 using System.Diagnostics;
13
14 internal class ScheduledObserver<T> : ObserverBase<T>, IDisposable
15 {
16 private volatile int _state = 0;
17 private const int STOPPED = 0;
18 private const int RUNNING = 1;
19 private const int PENDING = 2;
20 private const int FAULTED = 9;
21
22 private readonly ConcurrentQueue<T> _queue = new ConcurrentQueue<T>();
23 private volatile bool _failed;
24 private volatile Exception _error;
25 private volatile bool _completed;
26
27 private readonly IObserver<T> _observer;
28 private readonly IScheduler _scheduler;
29 private readonly ISchedulerLongRunning _longRunning;
30 private readonly SerialDisposable _disposable = new SerialDisposable();
31
32 public ScheduledObserver(IScheduler scheduler, IObserver<T> observer)
33 {
34 _scheduler = scheduler;
35 _observer = observer;
36 _longRunning = _scheduler.AsLongRunning();
37
38 if (_longRunning != null)
39 _dispatcherEvent = new SemaphoreSlim(0);
40 }
41
42 private readonly object _dispatcherInitGate = new object();
43 private SemaphoreSlim _dispatcherEvent;
44 private IDisposable _dispatcherJob;
45
46 private void EnsureDispatcher()
47 {
48 if (_dispatcherJob == null)
49 {
50 lock (_dispatcherInitGate)
51 {
52 if (_dispatcherJob == null)
53 {
54 _dispatcherJob = _longRunning.ScheduleLongRunning(Dispatch);
55
56 _disposable.Disposable = new CompositeDisposable(2)
57 {
58 _dispatcherJob,
59 Disposable.Create(() => _dispatcherEvent.Release())
60 };
61 }
62 }
63 }
64 }
65
66 private void Dispatch(ICancelable cancel)
67 {
68 while (true)
69 {
70 _dispatcherEvent.Wait();
71
72 if (cancel.IsDisposed)
73 return;
74
75 var next = default(T);
76 while (_queue.TryDequeue(out next))
77 {
78 try
79 {
80 _observer.OnNext(next);
81 }
82 catch
83 {
84 var nop = default(T);
85 while (_queue.TryDequeue(out nop))
86 ;
87
88 throw;
89 }
90
91 _dispatcherEvent.Wait();
92
93 if (cancel.IsDisposed)
94 return;
95 }
96
97 if (_failed)
98 {
99 _observer.OnError(_error);
100 Dispose();
101 return;
102 }
103
104 if (_completed)
105 {
106 _observer.OnCompleted();
107 Dispose();
108 return;
109 }
110 }
111 }
112
113 public void EnsureActive()
114 {
115 EnsureActive(1);
116 }
117
118 public void EnsureActive(int n)
119 {
120 if (_longRunning != null)
121 {
122 if (n > 0)
123 _dispatcherEvent.Release(n);
124
125 EnsureDispatcher();
126 }
127 else
128 EnsureActiveSlow();
129 }
130
131 private void EnsureActiveSlow()
132 {
133 var isOwner = false;
134
135 #pragma warning disable 0420
136 while (true)
137 {
138 var old = Interlocked.CompareExchange(ref _state, RUNNING, STOPPED);
139 if (old == STOPPED)
140 {
141 isOwner = true; // RUNNING
142 break;
143 }
144
145 if (old == FAULTED)
146 return;
147
148 // If we find the consumer loop running, we transition to PENDING to handle
149 // the case where the queue is seen empty by the consumer, making it transition
150 // to the STOPPED state, but we inserted an item into the queue.
151 //
152 // C: _queue.TryDequeue == false (RUNNING)
153 // ----------------------------------------------
154 // P: _queue.Enqueue(...)
155 // EnsureActive
156 // Exchange(ref _state, RUNNING) == RUNNING
157 // ----------------------------------------------
158 // C: transition to STOPPED (STOPPED)
159 //
160 // In this case, P would believe C is running and not invoke the scheduler
161 // using the isOwner flag.
162 //
163 // By introducing an intermediate PENDING state and using CAS in the consumer
164 // to only transition to STOPPED in case we were still RUNNING, we can force
165 // the consumer to reconsider the decision to transition to STOPPED. In that
166 // case, the consumer loops again and re-reads from the queue and other state
167 // fields. At least one bit of state will have changed because EnsureActive
168 // should only be called after invocation of IObserver<T> methods that touch
169 // this state.
170 //
171 if (old == PENDING || old == RUNNING && Interlocked.CompareExchange(ref _state, PENDING, RUNNING) == RUNNING)
172 break;
173 }
174 #pragma warning restore 0420
175
176 if (isOwner)
177 {
178 _disposable.Disposable = _scheduler.Schedule<object>(null, Run);
179 }
180 }
181
182 private void Run(object state, Action<object> recurse)
183 {
184 #pragma warning disable 0420
185 var next = default(T);
186 while (!_queue.TryDequeue(out next))
187 {
188 if (_failed)
189 {
190 // Between transitioning to _failed and the queue check in the loop,
191 // items could have been queued, so we can't stop yet. We don't spin
192 // and immediately re-check the queue.
193 //
194 // C: _queue.TryDequeue == false
195 // ----------------------------------------------
196 // P: OnNext(...)
197 // _queue.Enqueue(...) // Will get lost
198 // P: OnError(...)
199 // _failed = true
200 // ----------------------------------------------
201 // C: if (_failed)
202 // _observer.OnError(...) // Lost an OnNext
203 //
204 if (!_queue.IsEmpty)
205 continue;
206
207 Interlocked.Exchange(ref _state, STOPPED);
208 _observer.OnError(_error);
209 Dispose();
210 return;
211 }
212
213 if (_completed)
214 {
215 // Between transitioning to _completed and the queue check in the loop,
216 // items could have been queued, so we can't stop yet. We don't spin
217 // and immediately re-check the queue.
218 //
219 // C: _queue.TryDequeue == false
220 // ----------------------------------------------
221 // P: OnNext(...)
222 // _queue.Enqueue(...) // Will get lost
223 // P: OnCompleted(...)
224 // _completed = true
225 // ----------------------------------------------
226 // C: if (_completed)
227 // _observer.OnCompleted() // Lost an OnNext
228 //
229 if (!_queue.IsEmpty)
230 continue;
231
232 Interlocked.Exchange(ref _state, STOPPED);
233 _observer.OnCompleted();
234 Dispose();
235 return;
236 }
237
238 var old = Interlocked.CompareExchange(ref _state, STOPPED, RUNNING);
239 if (old == RUNNING || old == FAULTED)
240 return;
241
242 Debug.Assert(old == PENDING);
243
244 // The producer has put us in the PENDING state to prevent us from
245 // transitioning to STOPPED, so we go RUNNING again and re-check our state.
246 _state = RUNNING;
247 }
248
249 Interlocked.Exchange(ref _state, RUNNING);
250
251 #pragma warning restore 0420
252
253 try
254 {
255 _observer.OnNext(next);
256 }
257 catch
258 {
259 #pragma warning disable 0420
260 Interlocked.Exchange(ref _state, FAULTED);
261 #pragma warning restore 0420
262
263 var nop = default(T);
264 while (_queue.TryDequeue(out nop))
265 ;
266 throw;
267 }
268
269 recurse(state);
270 }
271
272 protected override void OnNextCore(T value)
273 {
274 _queue.Enqueue(value);
275 }
276
277 protected override void OnErrorCore(Exception exception)
278 {
279 _error = exception;
280 _failed = true;
281 }
282
283 protected override void OnCompletedCore()
284 {
285 _completed = true;
286 }
287
288 protected override void Dispose(bool disposing)
289 {
290 base.Dispose(disposing);
291
292 if (disposing)
293 {
294 _disposable.Dispose();
295 }
296 }
297 }
298 #else
299 class ScheduledObserver<T> : ObserverBase<T>, IDisposable
300 {
301 private bool _isAcquired = false;
302 private bool _hasFaulted = false;
303 private readonly Queue<Action> _queue = new Queue<Action>();
304 private readonly IObserver<T> _observer;
305 private readonly IScheduler _scheduler;
306 private readonly SerialDisposable _disposable = new SerialDisposable();
307
308 public ScheduledObserver(IScheduler scheduler, IObserver<T> observer)
309 {
310 _scheduler = scheduler;
311 _observer = observer;
312 }
313
314 public void EnsureActive(int n)
315 {
316 EnsureActive();
317 }
318
319 public void EnsureActive()
320 {
321 var isOwner = false;
322
323 lock (_queue)
324 {
325 if (!_hasFaulted && _queue.Count > 0)
326 {
327 isOwner = !_isAcquired;
328 _isAcquired = true;
329 }
330 }
331
332 if (isOwner)
333 {
334 _disposable.Disposable = _scheduler.Schedule<object>(null, Run);
335 }
336 }
337
338 private void Run(object state, Action<object> recurse)
339 {
340 var work = default(Action);
341 lock (_queue)
342 {
343 if (_queue.Count > 0)
344 work = _queue.Dequeue();
345 else
346 {
347 _isAcquired = false;
348 return;
349 }
350 }
351
352 try
353 {
354 work();
355 }
356 catch
357 {
358 lock (_queue)
359 {
360 _queue.Clear();
361 _hasFaulted = true;
362 }
363 throw;
364 }
365
366 recurse(state);
367 }
368
369 protected override void OnNextCore(T value)
370 {
371 lock (_queue)
372 _queue.Enqueue(() => _observer.OnNext(value));
373 }
374
375 protected override void OnErrorCore(Exception exception)
376 {
377 lock (_queue)
378 _queue.Enqueue(() => _observer.OnError(exception));
379 }
380
381 protected override void OnCompletedCore()
382 {
383 lock (_queue)
384 _queue.Enqueue(() => _observer.OnCompleted());
385 }
386
387 protected override void Dispose(bool disposing)
388 {
389 base.Dispose(disposing);
390
391 if (disposing)
392 {
393 _disposable.Dispose();
394 }
395 }
396 }
397 #endif
398
399 class ObserveOnObserver<T> : ScheduledObserver<T>
400 {
401 private IDisposable _cancel;
402
403 public ObserveOnObserver(IScheduler scheduler, IObserver<T> observer, IDisposable cancel)
404 : base(scheduler, observer)
405 {
406 _cancel = cancel;
407 }
408
409 protected override void OnNextCore(T value)
410 {
411 base.OnNextCore(value);
412 EnsureActive();
413 }
414
415 protected override void OnErrorCore(Exception exception)
416 {
417 base.OnErrorCore(exception);
418 EnsureActive();
419 }
420
421 protected override void OnCompletedCore()
422 {
423 base.OnCompletedCore();
424 EnsureActive();
425 }
426
427 protected override void Dispose(bool disposing)
428 {
429 base.Dispose(disposing);
430
431 if (disposing)
432 {
433 var cancel = Interlocked.Exchange(ref _cancel, null);
434 if (cancel != null)
435 {
436 cancel.Dispose();
437 }
438 }
439 }
440 }
441 }