Debian Codegraph @

external/rx/Rx/NET/Source/System.Reactive.Linq/Reactive/Linq/Observable/Latest.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
4 using System;
5 using System.Collections.Generic;
6 using System.Reactive.Threading;
7 using System.Threading;
8
9 namespace System.Reactive.Linq.ObservableImpl
10 {
11 class Latest<TSource> : PushToPullAdapter<TSource, TSource>
12 {
13 public Latest(IObservable<TSource> source)
14 : base(source)
15 {
16 }
17
18 protected override PushToPullSink<TSource, TSource> Run(IDisposable subscription)
19 {
20 return new _(subscription);
21 }
22
23 class _ : PushToPullSink<TSource, TSource>
24 {
25 private readonly object _gate;
26
27 #if !NO_CDS
28 private readonly SemaphoreSlim _semaphore;
29 #else
30 private readonly Semaphore _semaphore;
31 #endif
32
33 public _(IDisposable subscription)
34 : base(subscription)
35 {
36 _gate = new object();
37
38 #if !NO_CDS
39 _semaphore = new SemaphoreSlim(0, 1);
40 #else
41 _semaphore = new Semaphore(0, 1);
42 #endif
43 }
44
45 private bool _notificationAvailable;
46 private NotificationKind _kind;
47 private TSource _value;
48 private Exception _error;
49
50 public override void OnNext(TSource value)
51 {
52 var lackedValue = false;
53 lock (_gate)
54 {
55 lackedValue = !_notificationAvailable;
56 _notificationAvailable = true;
57 _kind = NotificationKind.OnNext;
58 _value = value;
59 }
60
61 if (lackedValue)
62 _semaphore.Release();
63 }
64
65 public override void OnError(Exception error)
66 {
67 base.Dispose();
68
69 var lackedValue = false;
70 lock (_gate)
71 {
72 lackedValue = !_notificationAvailable;
73 _notificationAvailable = true;
74 _kind = NotificationKind.OnError;
75 _error = error;
76 }
77
78 if (lackedValue)
79 _semaphore.Release();
80 }
81
82 public override void OnCompleted()
83 {
84 base.Dispose();
85
86 var lackedValue = false;
87 lock (_gate)
88 {
89 lackedValue = !_notificationAvailable;
90 _notificationAvailable = true;
91 _kind = NotificationKind.OnCompleted;
92 }
93
94 if (lackedValue)
95 _semaphore.Release();
96 }
97
98 public override bool TryMoveNext(out TSource current)
99 {
100 var kind = default(NotificationKind);
101 var value = default(TSource);
102 var error = default(Exception);
103
104 #if !NO_CDS
105 _semaphore.Wait();
106 #else
107 _semaphore.WaitOne();
108 #endif
109
110 lock (_gate)
111 {
112 kind = _kind;
113
114 switch (kind)
115 {
116 case NotificationKind.OnNext:
117 value = _value;
118 break;
119 case NotificationKind.OnError:
120 error = _error;
121 break;
122 }
123
124 _notificationAvailable = false;
125 }
126
127 switch (kind)
128 {
129 case NotificationKind.OnNext:
130 current = _value;
131 return true;
132 case NotificationKind.OnError:
133 error.Throw();
134 break;
135 case NotificationKind.OnCompleted:
136 break;
137 }
138
139 current = default(TSource);
140 return false;
141 }
142 }
143 }
144 }
145 #endif