Synchronization.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. using System.ComponentModel;
  5. using System.Reactive.Disposables;
  6. using System.Threading;
  7. namespace System.Reactive.Concurrency
  8. {
  9. /// <summary>
  10. /// Provides basic synchronization and scheduling services for observable sequences.
  11. /// </summary>
  12. [EditorBrowsable(EditorBrowsableState.Advanced)]
  13. public static class Synchronization
  14. {
  15. #region SubscribeOn
  16. /// <summary>
  17. /// Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler.
  18. /// </summary>
  19. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  20. /// <param name="source">Source sequence.</param>
  21. /// <param name="scheduler">Scheduler to perform subscription and unsubscription actions on.</param>
  22. /// <returns>The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.</returns>
  23. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="scheduler"/> is <c>null</c>.</exception>
  24. /// <remarks>
  25. /// Only the side-effects of subscribing to the source sequence and disposing subscriptions to the source sequence are run on the specified scheduler.
  26. /// In order to invoke observer callbacks on the specified scheduler, e.g. to offload callback processing to a dedicated thread, use <see cref="Synchronization.ObserveOn{TSource}(IObservable{TSource}, IScheduler)"/>.
  27. /// </remarks>
  28. public static IObservable<TSource> SubscribeOn<TSource>(IObservable<TSource> source, IScheduler scheduler)
  29. {
  30. if (source == null)
  31. throw new ArgumentNullException(nameof(source));
  32. if (scheduler == null)
  33. throw new ArgumentNullException(nameof(scheduler));
  34. return new AnonymousObservable<TSource>(observer =>
  35. {
  36. var m = new SingleAssignmentDisposable();
  37. var d = new SerialDisposable();
  38. d.Disposable = m;
  39. m.Disposable = scheduler.Schedule(() =>
  40. {
  41. d.Disposable = new ScheduledDisposable(scheduler, source.SubscribeSafe(observer));
  42. });
  43. return d;
  44. });
  45. }
  46. /// <summary>
  47. /// Wraps the source sequence in order to run its subscription and unsubscription logic on the specified synchronization context.
  48. /// </summary>
  49. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  50. /// <param name="source">Source sequence.</param>
  51. /// <param name="context">Synchronization context to perform subscription and unsubscription actions on.</param>
  52. /// <returns>The source sequence whose subscriptions and unsubscriptions happen on the specified synchronization context.</returns>
  53. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="context"/> is <c>null</c>.</exception>
  54. /// <remarks>
  55. /// Only the side-effects of subscribing to the source sequence and disposing subscriptions to the source sequence are run on the specified synchronization context.
  56. /// In order to invoke observer callbacks on the specified synchronization context, e.g. to post callbacks to a UI thread represented by the synchronization context, use <see cref="Synchronization.ObserveOn{TSource}(IObservable{TSource}, SynchronizationContext)"/>.
  57. /// </remarks>
  58. public static IObservable<TSource> SubscribeOn<TSource>(IObservable<TSource> source, SynchronizationContext context)
  59. {
  60. if (source == null)
  61. throw new ArgumentNullException(nameof(source));
  62. if (context == null)
  63. throw new ArgumentNullException(nameof(context));
  64. return new AnonymousObservable<TSource>(observer =>
  65. {
  66. var subscription = new SingleAssignmentDisposable();
  67. context.PostWithStartComplete(() =>
  68. {
  69. if (!subscription.IsDisposed)
  70. {
  71. subscription.Disposable = new ContextDisposable(context, source.SubscribeSafe(observer));
  72. }
  73. });
  74. return subscription;
  75. });
  76. }
  77. #endregion
  78. #region ObserveOn
  79. /// <summary>
  80. /// Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
  81. /// </summary>
  82. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  83. /// <param name="source">Source sequence.</param>
  84. /// <param name="scheduler">Scheduler to notify observers on.</param>
  85. /// <returns>The source sequence whose observations happen on the specified scheduler.</returns>
  86. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="scheduler"/> is <c>null</c>.</exception>
  87. public static IObservable<TSource> ObserveOn<TSource>(IObservable<TSource> source, IScheduler scheduler)
  88. {
  89. if (source == null)
  90. throw new ArgumentNullException(nameof(source));
  91. if (scheduler == null)
  92. throw new ArgumentNullException(nameof(scheduler));
  93. #if !NO_PERF
  94. return new ObserveOn<TSource>(source, scheduler);
  95. #else
  96. return new AnonymousObservable<TSource>(observer => source.Subscribe(new ObserveOnObserver<TSource>(scheduler, observer, null)));
  97. #endif
  98. }
  99. /// <summary>
  100. /// Wraps the source sequence in order to run its observer callbacks on the specified synchronization context.
  101. /// </summary>
  102. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  103. /// <param name="source">Source sequence.</param>
  104. /// <param name="context">Synchronization context to notify observers on.</param>
  105. /// <returns>The source sequence whose observations happen on the specified synchronization context.</returns>
  106. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="context"/> is <c>null</c>.</exception>
  107. public static IObservable<TSource> ObserveOn<TSource>(IObservable<TSource> source, SynchronizationContext context)
  108. {
  109. if (source == null)
  110. throw new ArgumentNullException(nameof(source));
  111. if (context == null)
  112. throw new ArgumentNullException(nameof(context));
  113. #if !NO_PERF
  114. return new ObserveOn<TSource>(source, context);
  115. #else
  116. return new AnonymousObservable<TSource>(observer =>
  117. {
  118. context.OperationStarted();
  119. return source.Subscribe(
  120. x => context.Post(_ =>
  121. {
  122. observer.OnNext(x);
  123. }, null),
  124. exception => context.Post(_ =>
  125. {
  126. observer.OnError(exception);
  127. }, null),
  128. () => context.Post(_ =>
  129. {
  130. observer.OnCompleted();
  131. }, null)
  132. ).Finally(() =>
  133. {
  134. context.OperationCompleted();
  135. });
  136. });
  137. #endif
  138. }
  139. #endregion
  140. #region Synchronize
  141. /// <summary>
  142. /// Wraps the source sequence in order to ensure observer callbacks are properly serialized.
  143. /// </summary>
  144. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  145. /// <param name="source">Source sequence.</param>
  146. /// <returns>The source sequence whose outgoing calls to observers are synchronized.</returns>
  147. /// <exception cref="ArgumentNullException"><paramref name="source"/> is <c>null</c>.</exception>
  148. public static IObservable<TSource> Synchronize<TSource>(IObservable<TSource> source)
  149. {
  150. if (source == null)
  151. throw new ArgumentNullException(nameof(source));
  152. #if !NO_PERF
  153. return new Synchronize<TSource>(source);
  154. #else
  155. return new AnonymousObservable<TSource>(observer =>
  156. {
  157. var gate = new object();
  158. return source.Subscribe(Observer.Synchronize(observer, gate));
  159. });
  160. #endif
  161. }
  162. /// <summary>
  163. /// Wraps the source sequence in order to ensure observer callbacks are synchronized using the specified gate object.
  164. /// </summary>
  165. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  166. /// <param name="source">Source sequence.</param>
  167. /// <param name="gate">Gate object to synchronize each observer call on.</param>
  168. /// <returns>The source sequence whose outgoing calls to observers are synchronized on the given gate object.</returns>
  169. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="gate"/> is <c>null</c>.</exception>
  170. public static IObservable<TSource> Synchronize<TSource>(IObservable<TSource> source, object gate)
  171. {
  172. if (source == null)
  173. throw new ArgumentNullException(nameof(source));
  174. if (gate == null)
  175. throw new ArgumentNullException(nameof(gate));
  176. #if !NO_PERF
  177. return new Synchronize<TSource>(source, gate);
  178. #else
  179. return new AnonymousObservable<TSource>(observer =>
  180. {
  181. return source.Subscribe(Observer.Synchronize(observer, gate));
  182. });
  183. #endif
  184. }
  185. #endregion
  186. }
  187. }