DispatcherScheduler.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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{TSource}(IObservable{TSource})"/> and <see cref="System.Reactive.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. throw new InvalidOperationException(Strings_WindowsThreading.NO_DISPATCHER_CURRENT_THREAD);
  32. return new DispatcherScheduler(dispatcher);
  33. }
  34. }
  35. /// <summary>
  36. /// Constructs a <see cref="DispatcherScheduler"/> that schedules units of work on the given <see cref="System.Windows.Threading.Dispatcher"/>.
  37. /// </summary>
  38. /// <param name="dispatcher"><see cref="DispatcherScheduler"/> to schedule work on.</param>
  39. /// <exception cref="ArgumentNullException"><paramref name="dispatcher"/> is <c>null</c>.</exception>
  40. public DispatcherScheduler(System.Windows.Threading.Dispatcher dispatcher)
  41. {
  42. if (dispatcher == null)
  43. throw new ArgumentNullException(nameof(dispatcher));
  44. Dispatcher = dispatcher;
  45. Priority = 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. if (dispatcher == null)
  56. throw new ArgumentNullException(nameof(dispatcher));
  57. Dispatcher = dispatcher;
  58. Priority = priority;
  59. }
  60. /// <summary>
  61. /// Gets the <see cref="System.Windows.Threading.Dispatcher"/> associated with the <see cref="DispatcherScheduler"/>.
  62. /// </summary>
  63. public System.Windows.Threading.Dispatcher Dispatcher { get; }
  64. /// <summary>
  65. /// Gets the priority at which work items will be dispatched.
  66. /// </summary>
  67. public System.Windows.Threading.DispatcherPriority Priority { get; }
  68. /// <summary>
  69. /// Schedules an action to be executed on the dispatcher.
  70. /// </summary>
  71. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  72. /// <param name="state">State passed to the action to be executed.</param>
  73. /// <param name="action">Action to be executed.</param>
  74. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  75. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  76. public override IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
  77. {
  78. if (action == null)
  79. throw new ArgumentNullException(nameof(action));
  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. throw new ArgumentNullException(nameof(action));
  106. var dt = Scheduler.Normalize(dueTime);
  107. if (dt.Ticks == 0)
  108. {
  109. return Schedule(state, action);
  110. }
  111. return ScheduleSlow(state, dt, action);
  112. }
  113. private IDisposable ScheduleSlow<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  114. {
  115. var d = new MultipleAssignmentDisposable();
  116. var timer = new System.Windows.Threading.DispatcherTimer(Priority, Dispatcher);
  117. timer.Tick += (s, e) =>
  118. {
  119. var t = Interlocked.Exchange(ref timer, null);
  120. if (t != null)
  121. {
  122. try
  123. {
  124. d.Disposable = action(this, state);
  125. }
  126. finally
  127. {
  128. t.Stop();
  129. action = null;
  130. }
  131. }
  132. };
  133. timer.Interval = dueTime;
  134. timer.Start();
  135. d.Disposable = Disposable.Create(() =>
  136. {
  137. var t = Interlocked.Exchange(ref timer, null);
  138. if (t != null)
  139. {
  140. t.Stop();
  141. action = (_, __) => Disposable.Empty;
  142. }
  143. });
  144. return d;
  145. }
  146. /// <summary>
  147. /// Schedules a periodic piece of work on the dispatcher, using a <see cref="System.Windows.Threading.DispatcherTimer"/> object.
  148. /// </summary>
  149. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  150. /// <param name="state">Initial state passed to the action upon the first iteration.</param>
  151. /// <param name="period">Period for running the work periodically.</param>
  152. /// <param name="action">Action to be executed, potentially updating the state.</param>
  153. /// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns>
  154. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  155. /// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than <see cref="TimeSpan.Zero"/>.</exception>
  156. public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action)
  157. {
  158. if (period < TimeSpan.Zero)
  159. throw new ArgumentOutOfRangeException(nameof(period));
  160. if (action == null)
  161. throw new ArgumentNullException(nameof(action));
  162. var timer = new System.Windows.Threading.DispatcherTimer(Priority, Dispatcher);
  163. var state1 = state;
  164. timer.Tick += (s, e) =>
  165. {
  166. state1 = action(state1);
  167. };
  168. timer.Interval = period;
  169. timer.Start();
  170. return Disposable.Create(() =>
  171. {
  172. var t = Interlocked.Exchange(ref timer, null);
  173. if (t != null)
  174. {
  175. t.Stop();
  176. action = _ => _;
  177. }
  178. });
  179. }
  180. }
  181. }
  182. #endif