Debian Codegraph @

external/rx/Rx/NET/Source/System.Reactive.Linq/Reactive/Linq/Observable/GetEnumerator.cs

raw
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 && !NO_CDS
4 using System;
5 using System.Collections.Concurrent;
6 using System.Collections.Generic;
7 using System.Diagnostics;
8 using System.Reactive.Disposables;
9 using System.Threading;
10
11 namespace System.Reactive.Linq.ObservableImpl
12 {
13 class GetEnumerator<TSource> : IEnumerator<TSource>, IObserver<TSource>
14 {
15 private readonly ConcurrentQueue<TSource> _queue;
16 private TSource _current;
17 private Exception _error;
18 private bool _done;
19 private bool _disposed;
20
21 private readonly SemaphoreSlim _gate;
22 private readonly SingleAssignmentDisposable _subscription;
23
24 public GetEnumerator()
25 {
26 _queue = new ConcurrentQueue<TSource>();
27 _gate = new SemaphoreSlim(0);
28 _subscription = new SingleAssignmentDisposable();
29 }
30
31 public IEnumerator<TSource> Run(IObservable<TSource> source)
32 {
33 //
34 // [OK] Use of unsafe Subscribe: non-pretentious exact mirror with the dual GetEnumerator method.
35 //
36 _subscription.Disposable = source.Subscribe/*Unsafe*/(this);
37 return this;
38 }
39
40 public void OnNext(TSource value)
41 {
42 _queue.Enqueue(value);
43 _gate.Release();
44 }
45
46 public void OnError(Exception error)
47 {
48 _error = error;
49 _subscription.Dispose();
50 _gate.Release();
51 }
52
53 public void OnCompleted()
54 {
55 _done = true;
56 _subscription.Dispose();
57 _gate.Release();
58 }
59
60 public bool MoveNext()
61 {
62 _gate.Wait();
63
64 if (_disposed)
65 throw new ObjectDisposedException("");
66
67 if (_queue.TryDequeue(out _current))
68 return true;
69
70 _error.ThrowIfNotNull();
71
72 Debug.Assert(_done);
73
74 _gate.Release(); // In the (rare) case the user calls MoveNext again we shouldn't block!
75 return false;
76 }
77
78 public TSource Current
79 {
80 get { return _current; }
81 }
82
83 object Collections.IEnumerator.Current
84 {
85 get { return _current; }
86 }
87
88 public void Dispose()
89 {
90 _subscription.Dispose();
91
92 _disposed = true;
93 _gate.Release();
94 }
95
96 public void Reset()
97 {
98 throw new NotSupportedException();
99 }
100 }
101 }
102 #endif