FromEvent.cs 17 KB

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