DispatcherScheduler.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. #if !WINDOWS
  5. using System.Reactive.Disposables;
  6. using System.Threading;
  7. namespace System.Reactive.Concurrency
  8. {
  9. /// <summary>
  10. /// Represents an object that schedules units of work on a <see cref="System.Windows.Threading.Dispatcher"/>.
  11. /// </summary>
  12. /// <remarks>
  13. /// This scheduler type is typically used indirectly through the <see cref="System.Reactive.Linq.DispatcherObservable.ObserveOnDispatcher&lt;TSource&gt;(IObservable&lt;TSource&gt;)"/> and <see cref="System.Reactive.Linq.DispatcherObservable.SubscribeOnDispatcher&lt;TSource&gt;(IObservable&lt;TSource&gt;)"/> methods that use the Dispatcher on the calling thread.
  14. /// </remarks>
  15. public class DispatcherScheduler : LocalScheduler, ISchedulerPeriodic
  16. {
  17. /// <summary>
  18. /// Gets the scheduler that schedules work on the current <see cref="System.Windows.Threading.Dispatcher"/>.
  19. /// </summary>
  20. [Obsolete(Constants_WindowsThreading.OBSOLETE_INSTANCE_PROPERTY)]
  21. public static DispatcherScheduler Instance
  22. {
  23. get
  24. {
  25. return new DispatcherScheduler(
  26. #if USE_SL_DISPATCHER
  27. System.Windows.Deployment.Current.Dispatcher
  28. #else
  29. System.Windows.Threading.Dispatcher.CurrentDispatcher
  30. #endif
  31. );
  32. }
  33. }
  34. /// <summary>
  35. /// Gets the scheduler that schedules work on the <see cref="System.Windows.Threading.Dispatcher"/> for the current thread.
  36. /// </summary>
  37. public static DispatcherScheduler Current
  38. {
  39. get
  40. {
  41. #if USE_SL_DISPATCHER
  42. return new DispatcherScheduler(System.Windows.Deployment.Current.Dispatcher);
  43. #else
  44. var dispatcher = System.Windows.Threading.Dispatcher.FromThread(Thread.CurrentThread);
  45. if (dispatcher == null)
  46. throw new InvalidOperationException(Strings_WindowsThreading.NO_DISPATCHER_CURRENT_THREAD);
  47. return new DispatcherScheduler(dispatcher);
  48. #endif
  49. }
  50. }
  51. System.Windows.Threading.Dispatcher _dispatcher;
  52. #if HAS_DISPATCHER_PRIORITY
  53. System.Windows.Threading.DispatcherPriority _priority;
  54. #endif
  55. /// <summary>
  56. /// Constructs a DispatcherScheduler that schedules units of work on the given <see cref="System.Windows.Threading.Dispatcher"/>.
  57. /// </summary>
  58. /// <param name="dispatcher">Dispatcher to schedule work on.</param>
  59. /// <exception cref="ArgumentNullException"><paramref name="dispatcher"/> is null.</exception>
  60. public DispatcherScheduler(System.Windows.Threading.Dispatcher dispatcher)
  61. {
  62. if (dispatcher == null)
  63. throw new ArgumentNullException(nameof(dispatcher));
  64. _dispatcher = dispatcher;
  65. #if HAS_DISPATCHER_PRIORITY
  66. _priority = Windows.Threading.DispatcherPriority.Normal;
  67. #endif
  68. }
  69. #if HAS_DISPATCHER_PRIORITY
  70. /// <summary>
  71. /// Constructs a DispatcherScheduler that schedules units of work on the given <see cref="System.Windows.Threading.Dispatcher"/> at the given priority.
  72. /// </summary>
  73. /// <param name="dispatcher">Dispatcher to schedule work on.</param>
  74. /// <param name="priority">Priority at which units of work are scheduled.</param>
  75. /// <exception cref="ArgumentNullException"><paramref name="dispatcher"/> is null.</exception>
  76. public DispatcherScheduler(System.Windows.Threading.Dispatcher dispatcher, System.Windows.Threading.DispatcherPriority priority)
  77. {
  78. if (dispatcher == null)
  79. throw new ArgumentNullException(nameof(dispatcher));
  80. _dispatcher = dispatcher;
  81. _priority = priority;
  82. }
  83. #endif
  84. /// <summary>
  85. /// Gets the <see cref="System.Windows.Threading.Dispatcher"/> associated with the DispatcherScheduler.
  86. /// </summary>
  87. public System.Windows.Threading.Dispatcher Dispatcher
  88. {
  89. get { return _dispatcher; }
  90. }
  91. #if HAS_DISPATCHER_PRIORITY
  92. /// <summary>
  93. /// Gets the priority at which work items will be dispatched.
  94. /// </summary>
  95. public System.Windows.Threading.DispatcherPriority Priority
  96. {
  97. get { return _priority; }
  98. }
  99. #endif
  100. /// <summary>
  101. /// Schedules an action to be executed on the dispatcher.
  102. /// </summary>
  103. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  104. /// <param name="state">State passed to the action to be executed.</param>
  105. /// <param name="action">Action to be executed.</param>
  106. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  107. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  108. public override IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
  109. {
  110. if (action == null)
  111. throw new ArgumentNullException(nameof(action));
  112. var d = new SingleAssignmentDisposable();
  113. _dispatcher.BeginInvoke(
  114. new Action(() =>
  115. {
  116. if (!d.IsDisposed)
  117. d.Disposable = action(this, state);
  118. })
  119. #if HAS_DISPATCHER_PRIORITY
  120. , _priority
  121. #endif
  122. );
  123. return d;
  124. }
  125. /// <summary>
  126. /// Schedules an action to be executed after dueTime on the dispatcher, using a <see cref="System.Windows.Threading.DispatcherTimer"/> object.
  127. /// </summary>
  128. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  129. /// <param name="state">State passed to the action to be executed.</param>
  130. /// <param name="action">Action to be executed.</param>
  131. /// <param name="dueTime">Relative time after which to execute the action.</param>
  132. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  133. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  134. public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  135. {
  136. if (action == null)
  137. throw new ArgumentNullException(nameof(action));
  138. var dt = Scheduler.Normalize(dueTime);
  139. if (dt.Ticks == 0)
  140. return Schedule(state, action);
  141. var d = new MultipleAssignmentDisposable();
  142. var timer = new System.Windows.Threading.DispatcherTimer(
  143. #if HAS_DISPATCHER_PRIORITY
  144. _priority, _dispatcher
  145. #elif DESKTOPCLR40 // BACKWARDS COMPATIBILITY with v1.x
  146. System.Windows.Threading.DispatcherPriority.Background, _dispatcher
  147. #endif
  148. );
  149. timer.Tick += (s, e) =>
  150. {
  151. var t = Interlocked.Exchange(ref timer, null);
  152. if (t != null)
  153. {
  154. try
  155. {
  156. d.Disposable = action(this, state);
  157. }
  158. finally
  159. {
  160. t.Stop();
  161. action = null;
  162. }
  163. }
  164. };
  165. timer.Interval = dt;
  166. timer.Start();
  167. d.Disposable = Disposable.Create(() =>
  168. {
  169. var t = Interlocked.Exchange(ref timer, null);
  170. if (t != null)
  171. {
  172. t.Stop();
  173. action = (_, __) => Disposable.Empty;
  174. }
  175. });
  176. return d;
  177. }
  178. /// <summary>
  179. /// Schedules a periodic piece of work on the dispatcher, using a <see cref="System.Windows.Threading.DispatcherTimer"/> object.
  180. /// </summary>
  181. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  182. /// <param name="state">Initial state passed to the action upon the first iteration.</param>
  183. /// <param name="period">Period for running the work periodically.</param>
  184. /// <param name="action">Action to be executed, potentially updating the state.</param>
  185. /// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns>
  186. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  187. /// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than TimeSpan.Zero.</exception>
  188. public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action)
  189. {
  190. if (period < TimeSpan.Zero)
  191. throw new ArgumentOutOfRangeException(nameof(period));
  192. if (action == null)
  193. throw new ArgumentNullException(nameof(action));
  194. var timer = new System.Windows.Threading.DispatcherTimer(
  195. #if HAS_DISPATCHER_PRIORITY
  196. _priority, _dispatcher
  197. #elif DESKTOPCLR40 // BACKWARDS COMPATIBILITY with v1.x
  198. System.Windows.Threading.DispatcherPriority.Background, _dispatcher
  199. #endif
  200. );
  201. var state1 = state;
  202. timer.Tick += (s, e) =>
  203. {
  204. state1 = action(state1);
  205. };
  206. timer.Interval = period;
  207. timer.Start();
  208. return Disposable.Create(() =>
  209. {
  210. var t = Interlocked.Exchange(ref timer, null);
  211. if (t != null)
  212. {
  213. t.Stop();
  214. action = _ => _;
  215. }
  216. });
  217. }
  218. }
  219. }
  220. #endif