Synchronization.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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 null.</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 null.</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. subscription.Disposable = new ContextDisposable(context, source.SubscribeSafe(observer));
  71. });
  72. return subscription;
  73. });
  74. }
  75. #endregion
  76. #region ObserveOn
  77. /// <summary>
  78. /// Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
  79. /// </summary>
  80. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  81. /// <param name="source">Source sequence.</param>
  82. /// <param name="scheduler">Scheduler to notify observers on.</param>
  83. /// <returns>The source sequence whose observations happen on the specified scheduler.</returns>
  84. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="scheduler"/> is null.</exception>
  85. public static IObservable<TSource> ObserveOn<TSource>(IObservable<TSource> source, IScheduler scheduler)
  86. {
  87. if (source == null)
  88. throw new ArgumentNullException(nameof(source));
  89. if (scheduler == null)
  90. throw new ArgumentNullException(nameof(scheduler));
  91. #if !NO_PERF
  92. return new ObserveOn<TSource>(source, scheduler);
  93. #else
  94. return new AnonymousObservable<TSource>(observer => source.Subscribe(new ObserveOnObserver<TSource>(scheduler, observer, null)));
  95. #endif
  96. }
  97. /// <summary>
  98. /// Wraps the source sequence in order to run its observer callbacks on the specified synchronization context.
  99. /// </summary>
  100. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  101. /// <param name="source">Source sequence.</param>
  102. /// <param name="context">Synchronization context to notify observers on.</param>
  103. /// <returns>The source sequence whose observations happen on the specified synchronization context.</returns>
  104. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="context"/> is null.</exception>
  105. public static IObservable<TSource> ObserveOn<TSource>(IObservable<TSource> source, SynchronizationContext context)
  106. {
  107. if (source == null)
  108. throw new ArgumentNullException(nameof(source));
  109. if (context == null)
  110. throw new ArgumentNullException(nameof(context));
  111. #if !NO_PERF
  112. return new ObserveOn<TSource>(source, context);
  113. #else
  114. return new AnonymousObservable<TSource>(observer =>
  115. {
  116. context.OperationStarted();
  117. return source.Subscribe(
  118. x => context.Post(_ =>
  119. {
  120. observer.OnNext(x);
  121. }, null),
  122. exception => context.Post(_ =>
  123. {
  124. observer.OnError(exception);
  125. }, null),
  126. () => context.Post(_ =>
  127. {
  128. observer.OnCompleted();
  129. }, null)
  130. ).Finally(() =>
  131. {
  132. context.OperationCompleted();
  133. });
  134. });
  135. #endif
  136. }
  137. #endregion
  138. #region Synchronize
  139. /// <summary>
  140. /// Wraps the source sequence in order to ensure observer callbacks are properly serialized.
  141. /// </summary>
  142. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  143. /// <param name="source">Source sequence.</param>
  144. /// <returns>The source sequence whose outgoing calls to observers are synchronized.</returns>
  145. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  146. public static IObservable<TSource> Synchronize<TSource>(IObservable<TSource> source)
  147. {
  148. if (source == null)
  149. throw new ArgumentNullException(nameof(source));
  150. #if !NO_PERF
  151. return new Synchronize<TSource>(source);
  152. #else
  153. return new AnonymousObservable<TSource>(observer =>
  154. {
  155. var gate = new object();
  156. return source.Subscribe(Observer.Synchronize(observer, gate));
  157. });
  158. #endif
  159. }
  160. /// <summary>
  161. /// Wraps the source sequence in order to ensure observer callbacks are synchronized using the specified gate object.
  162. /// </summary>
  163. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  164. /// <param name="source">Source sequence.</param>
  165. /// <param name="gate">Gate object to synchronize each observer call on.</param>
  166. /// <returns>The source sequence whose outgoing calls to observers are synchronized on the given gate object.</returns>
  167. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="gate"/> is null.</exception>
  168. public static IObservable<TSource> Synchronize<TSource>(IObservable<TSource> source, object gate)
  169. {
  170. if (source == null)
  171. throw new ArgumentNullException(nameof(source));
  172. if (gate == null)
  173. throw new ArgumentNullException(nameof(gate));
  174. #if !NO_PERF
  175. return new Synchronize<TSource>(source, gate);
  176. #else
  177. return new AnonymousObservable<TSource>(observer =>
  178. {
  179. return source.Subscribe(Observer.Synchronize(observer, gate));
  180. });
  181. #endif
  182. }
  183. #endregion
  184. }
  185. }