Debian Codegraph @

external/rx/Rx/NET/Source/System.Reactive.Linq/Reactive/Linq/Observable/FromEvent.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.Diagnostics;
6 using System.Reactive.Concurrency;
7 using System.Reactive.Disposables;
8 using System.Reactive.Subjects;
9
10 //
11 // BREAKING CHANGE v2 > v1.x - FromEvent[Pattern] now has an implicit SubscribeOn and Publish operation.
12 //
13 // The free-threaded nature of Rx is key to the performance characteristics of the event processing
14 // pipeline. However, in places where we bridge with the external world, this sometimes has negative
15 // effects due to thread-affine operations involved. The FromEvent[Pattern] bridges are one such
16 // place where we reach out to add and remove operations on events.
17 //
18 // Consider the following piece of code, assuming Rx v1.x usage:
19 //
20 // var txt = Observable.FromEventPattern(txtInput, "TextChanged");
21 // var res = from term in txt
22 // from word in svc.Lookup(term).TakeUntil(txt)
23 // select word;
24 //
25 // This code is flawed for various reasons. Seasoned Rx developers will immediately suggest usage of
26 // the Publish operator to share the side-effects of subscribing to the txt sequence, resulting in
27 // only one subscription to the event:
28 //
29 // var txt = Observable.FromEventPattern(txtInput, "TextChanged");
30 // var res = txt.Publish(txt_ => from term in txt_
31 // from word in svc.Lookup(term).TakeUntil(txt_)
32 // select word);
33 //
34 // Customers are typically confused as to why FromEvent[Pattern] causes multiple handlers to be added
35 // to the underlying event. This is in contrast with other From* bridges which involve the use of a
36 // subject (e.g. FromAsyncPattern, FromAsync, and ToObservable on Task<T>).
37 //
38 // But there are more issues with the code fragment above. Upon completion of the svc.Lookup(term)
39 // sequence, TakeUntil will unsubscribe from both sequences, causing the unsubscription to happen in
40 // the context of the source's OnCompleted, which may be the thread pool. Some thread-affine events
41 // don't quite like this. In UI frameworks like WPF and Silverlight, this turns out to be not much of
42 // a problem typically, but it's merely an accident things work out. From an e-mail conversion with
43 // the WPF/SL/Jupiter experts:
44 //
45 // "Unfortunately, as I expected, it’s confusing, and implementation details are showing through.
46 // The bottom line is that event add/remove should always be done on the right thread.
47 //
48 // Where events are implemented with compiler-generated code, i.e. MultiCastDelegate, the add/remove
49 // will be thread safe/agile. Where events are implemented in custom code, across Wpf/SL/WP/Jupiter,
50 // the add/remove are expected to happen on the Dispatcher thread.
51 //
52 // Jupiter actually has the consistent story here, where all the event add/remove implementations do
53 // the thread check. It should still be a “wrong thread” error, though, not an AV.
54 //
55 // In SL there’s a mix of core events (which do the thread check) and framework events (which use
56 // compiler-generated event implementations). So you get an exception if you unhook Button.Loaded
57 // from off thread, but you don’t get an exception if you unhook Button.Click.
58 //
59 // In WPF there’s a similar mix (some events are compiler-generated and some use the EventHandlerStore).
60 // But I don’t see any thread safety or thread check in the EventHandlerStore. So while it works, IIUC,
61 // it should have race conditions and corruptions."
62 //
63 // Starting with "Jupiter" (Windows XAML aka "Metro"), checks are added to ensure the add and remove
64 // operations for UI events are called from the UI thread. As a result, the dictionary suggest sample
65 // code shown above starts to fail. A possible fix is to use SubscribeOnDispatcher:
66 //
67 // var txt = Observable.FromEventPattern(txtInput, "TextChanged").SubscribeOnDispatcher();
68 // var res = from term in txt
69 // from word in svc.Lookup(term).TakeUntil(txt)
70 // select word;
71 //
72 // This fix has two problems:
73 //
74 // 1. Customers often don't quite understand the difference between ObserveOn and SubscribeOn. In fact,
75 // we've given guidance that use of the latter is typically indicative of a misunderstanding, and
76 // is used rarely. Also, the fragment above would likely be extended with some UI binding code where
77 // one needs to use ObserveOnDispatcher, so the combination of both becomes even more confusing.
78 //
79 // 2. There's a subtle race condition now. Upon receiving a new term from the txt sequence, SelectMany's
80 // invocation of the result selector involves TakeUntil subscribing to txt again. However, the use
81 // of SubscribeOnDispatcher means the subscription is now happening asynchronously, leaving a time
82 // gap between returning from Subscribe and doing the += on the underlying event:
83 //
84 // (Subscription of TakeUntil to txt)
85 // |
86 // v
87 // txt --------------------------------------------------------------
88 // |
89 // +-----...----+ (SubscribeOnDispatcher's post of Subscribe)
90 // |
91 // TextChanged ------"re"---------"rea"-------------"reac"-----"react"----...
92 // ^
93 // |
94 // (where += on the event happens)
95 //
96 // While this problem is rare and sometimes gets mitigated by accident because code is posting back
97 // to e.g. the UI message loop, it's extremely hard to debug when things go wrong.
98 //
99 // In order to fix this behavior such that code has the expected behavior, we do two things in Rx v2.0:
100 //
101 // - To solve the cross-thread add/remove handler operations and make them single-thread affine, we
102 // now do an implicit SubscribeOn with the SynchronizationContext.Current retrieved eagerly upon
103 // calling FromEvent[Pattern]. This goes hand-in-hand with a recommendation:
104 //
105 // "Always call FromEvent[Pattern] in a place where you'd normally write += and -= operations
106 // yourself. Don't inline the creation of a FromEvent[Pattern] object inside a query."
107 //
108 // This recommendation helps to keep code clean (bridging operations are moved outside queries) and
109 // ensures the captured SynchronizationContext is the least surprising one. E.g in the sample code
110 // above, the whole query likely lives in a button_Click handler or so.
111 //
112 // - To solve the time gap issue, we now add implicit Publish behavior with ref-counted behavior. In
113 // other words, the new FromEvent[Pattern] is pretty much the same as:
114 //
115 // Observable_v2.FromEvent[Pattern](<args>)
116 // ==
117 // Observable_v1.FromEvent[Pattern](<args>).SubscribeOn(SynchronizationContext.Current)
118 // .Publish()
119 // .RefCount()
120 //
121 // Overloads to FromEvent[Pattern] allow to specify the scheduler used for the SubscribeOn operation
122 // that's taking place internally. When omitted, a SynchronizationContextScheduler will be supplied
123 // if a current SynchronizationContext is found. If no current SynchronizationContext is found, the
124 // default scheduler is the immediate scheduler, falling back to the free-threaded behavior we had
125 // before in v1.x. (See GetSchedulerForCurrentContext in QueryLanguage.Events.cs).
126 //
127 // Notice a time gap can still occur at the point of the first subscription to the event sequence,
128 // or when the ref count fell back to zero. In cases of nested uses of the sequence (such as in the
129 // running example here), this is fine because the top-level subscription is kept alive for the whole
130 // duration. In other cases, there's already a race condition between the underlying event and the
131 // observable wrapper (assuming events are hot). For cold events that have side-effects upon add and
132 // remove handler operations, use of Observable.Create is recommended. This should be rather rare,
133 // as most events follow the typical MulticastDelegate implementation pattern:
134 //
135 // public event EventHandler<BarEventArgs> Bar;
136 //
137 // protected void OnBar(int value)
138 // {
139 // var bar = Bar;
140 // if (bar != null)
141 // bar(this, new BarEventArgs(value));
142 // }
143 //
144 // In here, there's already a race between the user hooking up an event handler through the += add
145 // operation and the event producer (possibly on a different thread) calling OnBar. It's also worth
146 // pointing out that this race condition is migitated by a check in SynchronizationContextScheduler
147 // causing synchronous execution in case the caller is already on the target SynchronizationContext.
148 // This situation is common when using FromEvent[Pattern] immediately after declaring it, e.g. in
149 // the context of a UI event handler.
150 //
151 // Finally, notice we can't simply connect the event to a Subject<T> upon a FromEvent[Pattern] call,
152 // because this would make it impossible to get rid of this one event handler (unless we expose some
153 // other means of resource maintenance, e.g. by making the returned object implement IDisposable).
154 // Also, this would cause the event producer to see the event's delegate in a non-null state all the
155 // time, causing event argument objects to be newed up, possibly sending those into a zero-observer
156 // subject (which is opaque to the event producer). Not to mention that the subject would always be
157 // rooted by the target event (even when the FromEvent[Pattern] observable wrapper is unreachable).
158 //
159 namespace System.Reactive.Linq.ObservableImpl
160 {
161 class FromEvent<TDelegate, TEventArgs> : ClassicEventProducer<TDelegate, TEventArgs>
162 {
163 private readonly Func<Action<TEventArgs>, TDelegate> _conversion;
164
165 public FromEvent(Action<TDelegate> addHandler, Action<TDelegate> removeHandler, IScheduler scheduler)
166 : base(addHandler, removeHandler, scheduler)
167 {
168 }
169
170 public FromEvent(Func<Action<TEventArgs>, TDelegate> conversion, Action<TDelegate> addHandler, Action<TDelegate> removeHandler, IScheduler scheduler)
171 : base(addHandler, removeHandler, scheduler)
172 {
173 _conversion = conversion;
174 }
175
176 protected override TDelegate GetHandler(Action<TEventArgs> onNext)
177 {
178 var handler = default(TDelegate);
179
180 if (_conversion == null)
181 {
182 handler = ReflectionUtils.CreateDelegate<TDelegate>(onNext, typeof(Action<TEventArgs>).GetMethod("Invoke"));
183 }
184 else
185 {
186 handler = _conversion(onNext);
187 }
188
189 return handler;
190 }
191 }
192
193 abstract class EventProducer<TDelegate, TArgs> : Producer<TArgs>
194 {
195 private readonly IScheduler _scheduler;
196 private readonly object _gate;
197
198 public EventProducer(IScheduler scheduler)
199 {
200 _scheduler = scheduler;
201 _gate = new object();
202 }
203
204 protected abstract TDelegate GetHandler(Action<TArgs> onNext);
205 protected abstract IDisposable AddHandler(TDelegate handler);
206
207 private Session _session;
208
209 protected override IDisposable Run(IObserver<TArgs> observer, IDisposable cancel, Action<IDisposable> setSink)
210 {
211 var connection = default(IDisposable);
212
213 lock (_gate)
214 {
215 //
216 // A session object holds on to a single handler to the underlying event, feeding
217 // into a subject. It also ref counts the number of connections to the subject.
218 //
219 // When the ref count goes back to zero, the event handler is unregistered, and
220 // the session will reach out to reset the _session field to null under the _gate
221 // lock. Future subscriptions will cause a new session to be created.
222 //
223 if (_session == null)
224 _session = new Session(this);
225
226 connection = _session.Connect(observer);
227 }
228
229 return connection;
230 }
231
232 class Session
233 {
234 private readonly EventProducer<TDelegate, TArgs> _parent;
235 private readonly Subject<TArgs> _subject;
236
237 private SingleAssignmentDisposable _removeHandler;
238 private int _count;
239
240 public Session(EventProducer<TDelegate, TArgs> parent)
241 {
242 _parent = parent;
243 _subject = new Subject<TArgs>();
244 }
245
246 public IDisposable Connect(IObserver<TArgs> observer)
247 {
248 /*
249 * CALLERS - Ensure this is called under the lock!
250 *
251 lock (_parent._gate) */
252 {
253 //
254 // We connect the given observer to the subject first, before performing any kind
255 // of initialization which will register an event handler. This is done to ensure
256 // we don't have a time gap between adding the handler and connecting the user's
257 // subject, e.g. when the ImmediateScheduler is used.
258 //
259 // [OK] Use of unsafe Subscribe: called on a known subject implementation.
260 //
261 var connection = _subject.Subscribe/*Unsafe*/(observer);
262
263 if (++_count == 1)
264 {
265 try
266 {
267 Initialize();
268 }
269 catch (Exception exception)
270 {
271 --_count;
272 connection.Dispose();
273
274 observer.OnError(exception);
275 return Disposable.Empty;
276 }
277 }
278
279 return Disposable.Create(() =>
280 {
281 connection.Dispose();
282
283 lock (_parent._gate)
284 {
285 if (--_count == 0)
286 {
287 _parent._scheduler.Schedule(_removeHandler.Dispose);
288 _parent._session = null;
289 }
290 }
291 });
292 }
293 }
294
295 private void Initialize()
296 {
297 /*
298 * CALLERS - Ensure this is called under the lock!
299 *
300 lock (_parent._gate) */
301 {
302 //
303 // When the ref count goes to zero, no-one should be able to perform operations on
304 // the session object anymore, because it gets nulled out.
305 //
306 Debug.Assert(_removeHandler == null);
307 _removeHandler = new SingleAssignmentDisposable();
308
309 //
310 // Conversion code is supposed to be a pure function and shouldn't be run on the
311 // scheduler, but the add handler call should. Notice the scheduler can be the
312 // ImmediateScheduler, causing synchronous invocation. This is the default when
313 // no SynchronizationContext is found (see QueryLanguage.Events.cs and search for
314 // the GetSchedulerForCurrentContext method).
315 //
316 var onNext = _parent.GetHandler(_subject.OnNext);
317 _parent._scheduler.Schedule(onNext, AddHandler);
318 }
319 }
320
321 private IDisposable AddHandler(IScheduler self, TDelegate onNext)
322 {
323 var removeHandler = default(IDisposable);
324 try
325 {
326 removeHandler = _parent.AddHandler(onNext);
327 }
328 catch (Exception exception)
329 {
330 _subject.OnError(exception);
331 return Disposable.Empty;
332 }
333
334 //
335 // We don't propagate the exception to the OnError channel upon Dispose. This is
336 // not possible at this stage, because we've already auto-detached in the base
337 // class Producer implementation. Even if we would switch the OnError and auto-
338 // detach calls, it wouldn't work because the remove handler logic is scheduled
339 // on the given scheduler, causing asynchrony. We can't block waiting for the
340 // remove handler to run on the scheduler.
341 //
342 _removeHandler.Disposable = removeHandler;
343
344 return Disposable.Empty;
345 }
346 }
347 }
348
349 abstract class ClassicEventProducer<TDelegate, TArgs> : EventProducer<TDelegate, TArgs>
350 {
351 private readonly Action<TDelegate> _addHandler;
352 private readonly Action<TDelegate> _removeHandler;
353
354 public ClassicEventProducer(Action<TDelegate> addHandler, Action<TDelegate> removeHandler, IScheduler scheduler)
355 : base(scheduler)
356 {
357 _addHandler = addHandler;
358 _removeHandler = removeHandler;
359 }
360
361 protected override IDisposable AddHandler(TDelegate handler)
362 {
363 _addHandler(handler);
364 return Disposable.Create(() => _removeHandler(handler));
365 }
366 }
367 }
368 #endif