DispatcherScheduler.cs 9.7 KB

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