DispatcherScheduler.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. #if HAS_WPF
  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="Linq.DispatcherObservable.ObserveOnDispatcher{TSource}(IObservable{TSource})"/> and <see cref="Linq.DispatcherObservable.SubscribeOnDispatcher{TSource}(IObservable{TSource})"/> 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 => new DispatcherScheduler(System.Windows.Threading.Dispatcher.CurrentDispatcher);
  22. /// <summary>
  23. /// Gets the scheduler that schedules work on the <see cref="System.Windows.Threading.Dispatcher"/> for the current thread.
  24. /// </summary>
  25. public static DispatcherScheduler Current
  26. {
  27. get
  28. {
  29. var dispatcher = System.Windows.Threading.Dispatcher.FromThread(Thread.CurrentThread);
  30. if (dispatcher == null)
  31. {
  32. throw new InvalidOperationException(Strings_WindowsThreading.NO_DISPATCHER_CURRENT_THREAD);
  33. }
  34. return new DispatcherScheduler(dispatcher);
  35. }
  36. }
  37. /// <summary>
  38. /// Constructs a <see cref="DispatcherScheduler"/> that schedules units of work on the given <see cref="System.Windows.Threading.Dispatcher"/>.
  39. /// </summary>
  40. /// <param name="dispatcher"><see cref="DispatcherScheduler"/> to schedule work on.</param>
  41. /// <exception cref="ArgumentNullException"><paramref name="dispatcher"/> is <c>null</c>.</exception>
  42. public DispatcherScheduler(System.Windows.Threading.Dispatcher dispatcher)
  43. {
  44. Dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
  45. Priority = System.Windows.Threading.DispatcherPriority.Normal;
  46. }
  47. /// <summary>
  48. /// Constructs a <see cref="DispatcherScheduler"/> that schedules units of work on the given <see cref="System.Windows.Threading.Dispatcher"/> at the given priority.
  49. /// </summary>
  50. /// <param name="dispatcher"><see cref="DispatcherScheduler"/> to schedule work on.</param>
  51. /// <param name="priority">Priority at which units of work are scheduled.</param>
  52. /// <exception cref="ArgumentNullException"><paramref name="dispatcher"/> is <c>null</c>.</exception>
  53. public DispatcherScheduler(System.Windows.Threading.Dispatcher dispatcher, System.Windows.Threading.DispatcherPriority priority)
  54. {
  55. Dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
  56. Priority = priority;
  57. }
  58. /// <summary>
  59. /// Gets the <see cref="System.Windows.Threading.Dispatcher"/> associated with the <see cref="DispatcherScheduler"/>.
  60. /// </summary>
  61. public System.Windows.Threading.Dispatcher Dispatcher { get; }
  62. /// <summary>
  63. /// Gets the priority at which work items will be dispatched.
  64. /// </summary>
  65. public System.Windows.Threading.DispatcherPriority Priority { get; }
  66. /// <summary>
  67. /// Schedules an action to be executed on the dispatcher.
  68. /// </summary>
  69. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  70. /// <param name="state">State passed to the action to be executed.</param>
  71. /// <param name="action">Action to be executed.</param>
  72. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  73. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  74. public override IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
  75. {
  76. if (action == null)
  77. {
  78. throw new ArgumentNullException(nameof(action));
  79. }
  80. var d = new SingleAssignmentDisposable();
  81. Dispatcher.BeginInvoke(
  82. new Action(() =>
  83. {
  84. if (!d.IsDisposed)
  85. {
  86. d.Disposable = action(this, state);
  87. }
  88. }),
  89. Priority
  90. );
  91. return d;
  92. }
  93. /// <summary>
  94. /// Schedules an action to be executed after <paramref name="dueTime"/> on the dispatcher, using a <see cref="System.Windows.Threading.DispatcherTimer"/> object.
  95. /// </summary>
  96. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  97. /// <param name="state">State passed to the action to be executed.</param>
  98. /// <param name="action">Action to be executed.</param>
  99. /// <param name="dueTime">Relative time after which to execute the action.</param>
  100. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  101. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  102. public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  103. {
  104. if (action == null)
  105. {
  106. throw new ArgumentNullException(nameof(action));
  107. }
  108. var dt = Scheduler.Normalize(dueTime);
  109. if (dt.Ticks == 0)
  110. {
  111. return Schedule(state, action);
  112. }
  113. return ScheduleSlow(state, dt, action);
  114. }
  115. private IDisposable ScheduleSlow<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  116. {
  117. var d = new MultipleAssignmentDisposable();
  118. var timer = new System.Windows.Threading.DispatcherTimer(Priority, Dispatcher);
  119. timer.Tick += (s, e) =>
  120. {
  121. var t = Interlocked.Exchange(ref timer, null);
  122. if (t != null)
  123. {
  124. try
  125. {
  126. d.Disposable = action(this, state);
  127. }
  128. finally
  129. {
  130. t.Stop();
  131. action = null;
  132. }
  133. }
  134. };
  135. timer.Interval = dueTime;
  136. timer.Start();
  137. d.Disposable = Disposable.Create(() =>
  138. {
  139. var t = Interlocked.Exchange(ref timer, null);
  140. if (t != null)
  141. {
  142. t.Stop();
  143. action = (_, __) => Disposable.Empty;
  144. }
  145. });
  146. return d;
  147. }
  148. /// <summary>
  149. /// Schedules a periodic piece of work on the dispatcher, using a <see cref="System.Windows.Threading.DispatcherTimer"/> object.
  150. /// </summary>
  151. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  152. /// <param name="state">Initial state passed to the action upon the first iteration.</param>
  153. /// <param name="period">Period for running the work periodically.</param>
  154. /// <param name="action">Action to be executed, potentially updating the state.</param>
  155. /// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns>
  156. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  157. /// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than <see cref="TimeSpan.Zero"/>.</exception>
  158. public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action)
  159. {
  160. if (period < TimeSpan.Zero)
  161. {
  162. throw new ArgumentOutOfRangeException(nameof(period));
  163. }
  164. if (action == null)
  165. {
  166. throw new ArgumentNullException(nameof(action));
  167. }
  168. var timer = new System.Windows.Threading.DispatcherTimer(Priority, Dispatcher);
  169. var state1 = state;
  170. timer.Tick += (s, e) =>
  171. {
  172. state1 = action(state1);
  173. };
  174. timer.Interval = period;
  175. timer.Start();
  176. return Disposable.Create(() =>
  177. {
  178. var t = Interlocked.Exchange(ref timer, null);
  179. if (t != null)
  180. {
  181. t.Stop();
  182. action = _ => _;
  183. }
  184. });
  185. }
  186. }
  187. }
  188. #endif