Synchronization.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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 SubscribeOnObservable<TSource>(source, scheduler);
  35. }
  36. sealed class SubscribeOnObservable<TSource> : ObservableBase<TSource>
  37. {
  38. private sealed class Subscription : IDisposable
  39. {
  40. private IDisposable _cancel;
  41. public Subscription(IObservable<TSource> source, IScheduler scheduler, IObserver<TSource> observer)
  42. {
  43. Disposable.TrySetSingle(
  44. ref _cancel,
  45. scheduler.Schedule(
  46. (@this: this, source, observer),
  47. (closureScheduler, state) =>
  48. {
  49. Disposable.TrySetSerial(ref state.@this._cancel, new ScheduledDisposable(closureScheduler, state.source.SubscribeSafe(state.observer)));
  50. return Disposable.Empty;
  51. }));
  52. }
  53. public void Dispose()
  54. {
  55. Disposable.TryDispose(ref _cancel);
  56. }
  57. }
  58. readonly IObservable<TSource> source;
  59. readonly IScheduler scheduler;
  60. public SubscribeOnObservable(IObservable<TSource> source, IScheduler scheduler)
  61. {
  62. this.source = source;
  63. this.scheduler = scheduler;
  64. }
  65. protected override IDisposable SubscribeCore(IObserver<TSource> observer)
  66. {
  67. return new Subscription(source, scheduler, observer);
  68. }
  69. }
  70. /// <summary>
  71. /// Wraps the source sequence in order to run its subscription and unsubscription logic on the specified synchronization context.
  72. /// </summary>
  73. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  74. /// <param name="source">Source sequence.</param>
  75. /// <param name="context">Synchronization context to perform subscription and unsubscription actions on.</param>
  76. /// <returns>The source sequence whose subscriptions and unsubscriptions happen on the specified synchronization context.</returns>
  77. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="context"/> is <c>null</c>.</exception>
  78. /// <remarks>
  79. /// Only the side-effects of subscribing to the source sequence and disposing subscriptions to the source sequence are run on the specified synchronization context.
  80. /// 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)"/>.
  81. /// </remarks>
  82. public static IObservable<TSource> SubscribeOn<TSource>(IObservable<TSource> source, SynchronizationContext context)
  83. {
  84. if (source == null)
  85. throw new ArgumentNullException(nameof(source));
  86. if (context == null)
  87. throw new ArgumentNullException(nameof(context));
  88. return new SubscribeOnCtxObservable<TSource>(source, context);
  89. }
  90. sealed class SubscribeOnCtxObservable<TSource> : ObservableBase<TSource>
  91. {
  92. private sealed class Subscription : IDisposable
  93. {
  94. private readonly IObservable<TSource> _source;
  95. private readonly IObserver<TSource> _observer;
  96. private readonly SynchronizationContext _context;
  97. private IDisposable _cancel;
  98. public Subscription(IObservable<TSource> source, SynchronizationContext context, IObserver<TSource> observer)
  99. {
  100. _source = source;
  101. _context = context;
  102. _observer = observer;
  103. context.PostWithStartComplete(
  104. @this =>
  105. {
  106. if (!Disposable.GetIsDisposed(ref @this._cancel))
  107. {
  108. Disposable.SetSingle(ref @this._cancel, new ContextDisposable(@this._context, @this._source.SubscribeSafe(@this._observer)));
  109. }
  110. },
  111. this);
  112. }
  113. public void Dispose()
  114. {
  115. Disposable.TryDispose(ref _cancel);
  116. }
  117. }
  118. readonly IObservable<TSource> _source;
  119. readonly SynchronizationContext _context;
  120. public SubscribeOnCtxObservable(IObservable<TSource> source, SynchronizationContext context)
  121. {
  122. _source = source;
  123. _context = context;
  124. }
  125. protected override IDisposable SubscribeCore(IObserver<TSource> observer)
  126. {
  127. return new Subscription(_source, _context, observer);
  128. }
  129. }
  130. #endregion
  131. #region ObserveOn
  132. /// <summary>
  133. /// Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
  134. /// </summary>
  135. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  136. /// <param name="source">Source sequence.</param>
  137. /// <param name="scheduler">Scheduler to notify observers on.</param>
  138. /// <returns>The source sequence whose observations happen on the specified scheduler.</returns>
  139. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="scheduler"/> is <c>null</c>.</exception>
  140. public static IObservable<TSource> ObserveOn<TSource>(IObservable<TSource> source, IScheduler scheduler)
  141. {
  142. if (source == null)
  143. throw new ArgumentNullException(nameof(source));
  144. if (scheduler == null)
  145. throw new ArgumentNullException(nameof(scheduler));
  146. return new ObserveOn<TSource>.Scheduler(source, scheduler);
  147. }
  148. /// <summary>
  149. /// Wraps the source sequence in order to run its observer callbacks on the specified synchronization context.
  150. /// </summary>
  151. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  152. /// <param name="source">Source sequence.</param>
  153. /// <param name="context">Synchronization context to notify observers on.</param>
  154. /// <returns>The source sequence whose observations happen on the specified synchronization context.</returns>
  155. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="context"/> is <c>null</c>.</exception>
  156. public static IObservable<TSource> ObserveOn<TSource>(IObservable<TSource> source, SynchronizationContext context)
  157. {
  158. if (source == null)
  159. throw new ArgumentNullException(nameof(source));
  160. if (context == null)
  161. throw new ArgumentNullException(nameof(context));
  162. return new ObserveOn<TSource>.Context(source, context);
  163. }
  164. #endregion
  165. #region Synchronize
  166. /// <summary>
  167. /// Wraps the source sequence in order to ensure observer callbacks are properly serialized.
  168. /// </summary>
  169. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  170. /// <param name="source">Source sequence.</param>
  171. /// <returns>The source sequence whose outgoing calls to observers are synchronized.</returns>
  172. /// <exception cref="ArgumentNullException"><paramref name="source"/> is <c>null</c>.</exception>
  173. public static IObservable<TSource> Synchronize<TSource>(IObservable<TSource> source)
  174. {
  175. if (source == null)
  176. throw new ArgumentNullException(nameof(source));
  177. return new Synchronize<TSource>(source);
  178. }
  179. /// <summary>
  180. /// Wraps the source sequence in order to ensure observer callbacks are synchronized using the specified gate object.
  181. /// </summary>
  182. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  183. /// <param name="source">Source sequence.</param>
  184. /// <param name="gate">Gate object to synchronize each observer call on.</param>
  185. /// <returns>The source sequence whose outgoing calls to observers are synchronized on the given gate object.</returns>
  186. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="gate"/> is <c>null</c>.</exception>
  187. public static IObservable<TSource> Synchronize<TSource>(IObservable<TSource> source, object gate)
  188. {
  189. if (source == null)
  190. throw new ArgumentNullException(nameof(source));
  191. if (gate == null)
  192. throw new ArgumentNullException(nameof(gate));
  193. return new Synchronize<TSource>(source, gate);
  194. }
  195. #endregion
  196. }
  197. }