Synchronization.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. #nullable disable
  5. using System.ComponentModel;
  6. using System.Reactive.Disposables;
  7. using System.Threading;
  8. namespace System.Reactive.Concurrency
  9. {
  10. /// <summary>
  11. /// Provides basic synchronization and scheduling services for observable sequences.
  12. /// </summary>
  13. [EditorBrowsable(EditorBrowsableState.Advanced)]
  14. public static class Synchronization
  15. {
  16. #region SubscribeOn
  17. /// <summary>
  18. /// Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler.
  19. /// </summary>
  20. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  21. /// <param name="source">Source sequence.</param>
  22. /// <param name="scheduler">Scheduler to perform subscription and unsubscription actions on.</param>
  23. /// <returns>The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.</returns>
  24. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="scheduler"/> is <c>null</c>.</exception>
  25. /// <remarks>
  26. /// Only the side-effects of subscribing to the source sequence and disposing subscriptions to the source sequence are run on the specified scheduler.
  27. /// 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)"/>.
  28. /// </remarks>
  29. public static IObservable<TSource> SubscribeOn<TSource>(IObservable<TSource> source, IScheduler scheduler)
  30. {
  31. if (source == null)
  32. {
  33. throw new ArgumentNullException(nameof(source));
  34. }
  35. if (scheduler == null)
  36. {
  37. throw new ArgumentNullException(nameof(scheduler));
  38. }
  39. return new SubscribeOnObservable<TSource>(source, scheduler);
  40. }
  41. private sealed class SubscribeOnObservable<TSource> : ObservableBase<TSource>
  42. {
  43. private sealed class Subscription : IDisposable
  44. {
  45. private IDisposable _cancel;
  46. public Subscription(IObservable<TSource> source, IScheduler scheduler, IObserver<TSource> observer)
  47. {
  48. Disposable.TrySetSingle(
  49. ref _cancel,
  50. scheduler.Schedule(
  51. (@this: this, source, observer),
  52. (closureScheduler, state) =>
  53. {
  54. Disposable.TrySetSerial(ref state.@this._cancel, new ScheduledDisposable(closureScheduler, state.source.SubscribeSafe(state.observer)));
  55. return Disposable.Empty;
  56. }));
  57. }
  58. public void Dispose()
  59. {
  60. Disposable.TryDispose(ref _cancel);
  61. }
  62. }
  63. private readonly IObservable<TSource> _source;
  64. private readonly IScheduler _scheduler;
  65. public SubscribeOnObservable(IObservable<TSource> source, IScheduler scheduler)
  66. {
  67. _source = source;
  68. _scheduler = scheduler;
  69. }
  70. protected override IDisposable SubscribeCore(IObserver<TSource> observer)
  71. {
  72. return new Subscription(_source, _scheduler, observer);
  73. }
  74. }
  75. /// <summary>
  76. /// Wraps the source sequence in order to run its subscription and unsubscription logic on the specified synchronization context.
  77. /// </summary>
  78. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  79. /// <param name="source">Source sequence.</param>
  80. /// <param name="context">Synchronization context to perform subscription and unsubscription actions on.</param>
  81. /// <returns>The source sequence whose subscriptions and unsubscriptions happen on the specified synchronization context.</returns>
  82. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="context"/> is <c>null</c>.</exception>
  83. /// <remarks>
  84. /// Only the side-effects of subscribing to the source sequence and disposing subscriptions to the source sequence are run on the specified synchronization context.
  85. /// 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)"/>.
  86. /// </remarks>
  87. public static IObservable<TSource> SubscribeOn<TSource>(IObservable<TSource> source, SynchronizationContext context)
  88. {
  89. if (source == null)
  90. {
  91. throw new ArgumentNullException(nameof(source));
  92. }
  93. if (context == null)
  94. {
  95. throw new ArgumentNullException(nameof(context));
  96. }
  97. return new SubscribeOnCtxObservable<TSource>(source, context);
  98. }
  99. private sealed class SubscribeOnCtxObservable<TSource> : ObservableBase<TSource>
  100. {
  101. private sealed class Subscription : IDisposable
  102. {
  103. private readonly IObservable<TSource> _source;
  104. private readonly IObserver<TSource> _observer;
  105. private readonly SynchronizationContext _context;
  106. private IDisposable _cancel;
  107. public Subscription(IObservable<TSource> source, SynchronizationContext context, IObserver<TSource> observer)
  108. {
  109. _source = source;
  110. _context = context;
  111. _observer = observer;
  112. context.PostWithStartComplete(
  113. @this =>
  114. {
  115. if (!Disposable.GetIsDisposed(ref @this._cancel))
  116. {
  117. Disposable.SetSingle(ref @this._cancel, new ContextDisposable(@this._context, @this._source.SubscribeSafe(@this._observer)));
  118. }
  119. },
  120. this);
  121. }
  122. public void Dispose()
  123. {
  124. Disposable.TryDispose(ref _cancel);
  125. }
  126. }
  127. private readonly IObservable<TSource> _source;
  128. private readonly SynchronizationContext _context;
  129. public SubscribeOnCtxObservable(IObservable<TSource> source, SynchronizationContext context)
  130. {
  131. _source = source;
  132. _context = context;
  133. }
  134. protected override IDisposable SubscribeCore(IObserver<TSource> observer)
  135. {
  136. return new Subscription(_source, _context, observer);
  137. }
  138. }
  139. #endregion
  140. #region ObserveOn
  141. /// <summary>
  142. /// Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
  143. /// </summary>
  144. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  145. /// <param name="source">Source sequence.</param>
  146. /// <param name="scheduler">Scheduler to notify observers on.</param>
  147. /// <returns>The source sequence whose observations happen on the specified scheduler.</returns>
  148. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="scheduler"/> is <c>null</c>.</exception>
  149. public static IObservable<TSource> ObserveOn<TSource>(IObservable<TSource> source, IScheduler scheduler)
  150. {
  151. if (source == null)
  152. {
  153. throw new ArgumentNullException(nameof(source));
  154. }
  155. if (scheduler == null)
  156. {
  157. throw new ArgumentNullException(nameof(scheduler));
  158. }
  159. var longRunning = scheduler.AsLongRunning();
  160. if (longRunning != null)
  161. {
  162. return new ObserveOn<TSource>.SchedulerLongRunning(source, longRunning);
  163. }
  164. return new ObserveOn<TSource>.Scheduler(source, scheduler);
  165. }
  166. /// <summary>
  167. /// Wraps the source sequence in order to run its observer callbacks on the specified synchronization context.
  168. /// </summary>
  169. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  170. /// <param name="source">Source sequence.</param>
  171. /// <param name="context">Synchronization context to notify observers on.</param>
  172. /// <returns>The source sequence whose observations happen on the specified synchronization context.</returns>
  173. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="context"/> is <c>null</c>.</exception>
  174. public static IObservable<TSource> ObserveOn<TSource>(IObservable<TSource> source, SynchronizationContext context)
  175. {
  176. if (source == null)
  177. {
  178. throw new ArgumentNullException(nameof(source));
  179. }
  180. if (context == null)
  181. {
  182. throw new ArgumentNullException(nameof(context));
  183. }
  184. return new ObserveOn<TSource>.Context(source, context);
  185. }
  186. #endregion
  187. #region Synchronize
  188. /// <summary>
  189. /// Wraps the source sequence in order to ensure observer callbacks are properly serialized.
  190. /// </summary>
  191. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  192. /// <param name="source">Source sequence.</param>
  193. /// <returns>The source sequence whose outgoing calls to observers are synchronized.</returns>
  194. /// <exception cref="ArgumentNullException"><paramref name="source"/> is <c>null</c>.</exception>
  195. public static IObservable<TSource> Synchronize<TSource>(IObservable<TSource> source)
  196. {
  197. if (source == null)
  198. {
  199. throw new ArgumentNullException(nameof(source));
  200. }
  201. return new Synchronize<TSource>(source);
  202. }
  203. /// <summary>
  204. /// Wraps the source sequence in order to ensure observer callbacks are synchronized using the specified gate object.
  205. /// </summary>
  206. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  207. /// <param name="source">Source sequence.</param>
  208. /// <param name="gate">Gate object to synchronize each observer call on.</param>
  209. /// <returns>The source sequence whose outgoing calls to observers are synchronized on the given gate object.</returns>
  210. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="gate"/> is <c>null</c>.</exception>
  211. public static IObservable<TSource> Synchronize<TSource>(IObservable<TSource> source, object gate)
  212. {
  213. if (source == null)
  214. {
  215. throw new ArgumentNullException(nameof(source));
  216. }
  217. if (gate == null)
  218. {
  219. throw new ArgumentNullException(nameof(gate));
  220. }
  221. return new Synchronize<TSource>(source, gate);
  222. }
  223. #endregion
  224. }
  225. }