FromEvent.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. #if !NO_PERF
  5. using System;
  6. using System.Diagnostics;
  7. using System.Reactive.Concurrency;
  8. using System.Reactive.Disposables;
  9. using System.Reactive.Subjects;
  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. public FromEvent(Action<TDelegate> addHandler, Action<TDelegate> removeHandler, IScheduler scheduler)
  165. : base(addHandler, removeHandler, scheduler)
  166. {
  167. }
  168. public FromEvent(Func<Action<TEventArgs>, TDelegate> conversion, Action<TDelegate> addHandler, Action<TDelegate> removeHandler, IScheduler scheduler)
  169. : base(addHandler, removeHandler, scheduler)
  170. {
  171. _conversion = conversion;
  172. }
  173. protected override TDelegate GetHandler(Action<TEventArgs> onNext)
  174. {
  175. var handler = default(TDelegate);
  176. if (_conversion == null)
  177. {
  178. handler = ReflectionUtils.CreateDelegate<TDelegate>(onNext, typeof(Action<TEventArgs>).GetMethod(nameof(Action<TEventArgs>.Invoke)));
  179. }
  180. else
  181. {
  182. handler = _conversion(onNext);
  183. }
  184. return handler;
  185. }
  186. }
  187. abstract class EventProducer<TDelegate, TArgs> : Producer<TArgs>
  188. {
  189. private readonly IScheduler _scheduler;
  190. private readonly object _gate;
  191. public EventProducer(IScheduler scheduler)
  192. {
  193. _scheduler = scheduler;
  194. _gate = new object();
  195. }
  196. protected abstract TDelegate GetHandler(Action<TArgs> onNext);
  197. protected abstract IDisposable AddHandler(TDelegate handler);
  198. private Session _session;
  199. protected override IDisposable Run(IObserver<TArgs> observer, IDisposable cancel, Action<IDisposable> setSink)
  200. {
  201. var connection = default(IDisposable);
  202. lock (_gate)
  203. {
  204. //
  205. // A session object holds on to a single handler to the underlying event, feeding
  206. // into a subject. It also ref counts the number of connections to the subject.
  207. //
  208. // When the ref count goes back to zero, the event handler is unregistered, and
  209. // the session will reach out to reset the _session field to null under the _gate
  210. // lock. Future subscriptions will cause a new session to be created.
  211. //
  212. if (_session == null)
  213. _session = new Session(this);
  214. connection = _session.Connect(observer);
  215. }
  216. return connection;
  217. }
  218. class Session
  219. {
  220. private readonly EventProducer<TDelegate, TArgs> _parent;
  221. private readonly Subject<TArgs> _subject;
  222. private SingleAssignmentDisposable _removeHandler;
  223. private int _count;
  224. public Session(EventProducer<TDelegate, TArgs> parent)
  225. {
  226. _parent = parent;
  227. _subject = new Subject<TArgs>();
  228. }
  229. public IDisposable Connect(IObserver<TArgs> observer)
  230. {
  231. /*
  232. * CALLERS - Ensure this is called under the lock!
  233. *
  234. lock (_parent._gate) */
  235. {
  236. //
  237. // We connect the given observer to the subject first, before performing any kind
  238. // of initialization which will register an event handler. This is done to ensure
  239. // we don't have a time gap between adding the handler and connecting the user's
  240. // subject, e.g. when the ImmediateScheduler is used.
  241. //
  242. // [OK] Use of unsafe Subscribe: called on a known subject implementation.
  243. //
  244. var connection = _subject.Subscribe/*Unsafe*/(observer);
  245. if (++_count == 1)
  246. {
  247. try
  248. {
  249. Initialize();
  250. }
  251. catch (Exception exception)
  252. {
  253. --_count;
  254. connection.Dispose();
  255. observer.OnError(exception);
  256. return Disposable.Empty;
  257. }
  258. }
  259. return Disposable.Create(() =>
  260. {
  261. connection.Dispose();
  262. lock (_parent._gate)
  263. {
  264. if (--_count == 0)
  265. {
  266. _parent._scheduler.Schedule(_removeHandler.Dispose);
  267. _parent._session = null;
  268. }
  269. }
  270. });
  271. }
  272. }
  273. private void Initialize()
  274. {
  275. /*
  276. * CALLERS - Ensure this is called under the lock!
  277. *
  278. lock (_parent._gate) */
  279. {
  280. //
  281. // When the ref count goes to zero, no-one should be able to perform operations on
  282. // the session object anymore, because it gets nulled out.
  283. //
  284. Debug.Assert(_removeHandler == null);
  285. _removeHandler = new SingleAssignmentDisposable();
  286. //
  287. // Conversion code is supposed to be a pure function and shouldn't be run on the
  288. // scheduler, but the add handler call should. Notice the scheduler can be the
  289. // ImmediateScheduler, causing synchronous invocation. This is the default when
  290. // no SynchronizationContext is found (see QueryLanguage.Events.cs and search for
  291. // the GetSchedulerForCurrentContext method).
  292. //
  293. var onNext = _parent.GetHandler(_subject.OnNext);
  294. _parent._scheduler.Schedule(onNext, AddHandler);
  295. }
  296. }
  297. private IDisposable AddHandler(IScheduler self, TDelegate onNext)
  298. {
  299. var removeHandler = default(IDisposable);
  300. try
  301. {
  302. removeHandler = _parent.AddHandler(onNext);
  303. }
  304. catch (Exception exception)
  305. {
  306. _subject.OnError(exception);
  307. return Disposable.Empty;
  308. }
  309. //
  310. // We don't propagate the exception to the OnError channel upon Dispose. This is
  311. // not possible at this stage, because we've already auto-detached in the base
  312. // class Producer implementation. Even if we would switch the OnError and auto-
  313. // detach calls, it wouldn't work because the remove handler logic is scheduled
  314. // on the given scheduler, causing asynchrony. We can't block waiting for the
  315. // remove handler to run on the scheduler.
  316. //
  317. _removeHandler.Disposable = removeHandler;
  318. return Disposable.Empty;
  319. }
  320. }
  321. }
  322. abstract class ClassicEventProducer<TDelegate, TArgs> : EventProducer<TDelegate, TArgs>
  323. {
  324. private readonly Action<TDelegate> _addHandler;
  325. private readonly Action<TDelegate> _removeHandler;
  326. public ClassicEventProducer(Action<TDelegate> addHandler, Action<TDelegate> removeHandler, IScheduler scheduler)
  327. : base(scheduler)
  328. {
  329. _addHandler = addHandler;
  330. _removeHandler = removeHandler;
  331. }
  332. protected override IDisposable AddHandler(TDelegate handler)
  333. {
  334. _addHandler(handler);
  335. return Disposable.Create(() => _removeHandler(handler));
  336. }
  337. }
  338. }
  339. #endif