CoreDispatcherScheduler.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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.Concurrency;
  6. using System.Reactive.Disposables;
  7. using System.Runtime.ExceptionServices;
  8. using System.Threading;
  9. using Windows.UI.Core;
  10. using Windows.UI.Xaml;
  11. namespace System.Reactive.Concurrency
  12. {
  13. /// <summary>
  14. /// Represents an object that schedules units of work on a Windows.UI.Core.CoreDispatcher.
  15. /// </summary>
  16. /// <remarks>
  17. /// 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 current Dispatcher.
  18. /// </remarks>
  19. [CLSCompliant(false)]
  20. public sealed class CoreDispatcherScheduler : LocalScheduler, ISchedulerPeriodic
  21. {
  22. private readonly CoreDispatcher _dispatcher;
  23. private readonly CoreDispatcherPriority _priority;
  24. /// <summary>
  25. /// Constructs a CoreDispatcherScheduler that schedules units of work on the given Windows.UI.Core.CoreDispatcher.
  26. /// </summary>
  27. /// <param name="dispatcher">Dispatcher to schedule work on.</param>
  28. /// <exception cref="ArgumentNullException"><paramref name="dispatcher"/> is null.</exception>
  29. public CoreDispatcherScheduler(CoreDispatcher dispatcher)
  30. {
  31. if (dispatcher == null)
  32. throw new ArgumentNullException("dispatcher");
  33. _dispatcher = dispatcher;
  34. _priority = CoreDispatcherPriority.Normal;
  35. }
  36. /// <summary>
  37. /// Constructs a CoreDispatcherScheduler that schedules units of work on the given Windows.UI.Core.CoreDispatcher with the given priority.
  38. /// </summary>
  39. /// <param name="dispatcher">Dispatcher to schedule work on.</param>
  40. /// <param name="priority">Priority for scheduled units of work.</param>
  41. /// <exception cref="ArgumentNullException"><paramref name="dispatcher"/> is null.</exception>
  42. public CoreDispatcherScheduler(CoreDispatcher dispatcher, CoreDispatcherPriority priority)
  43. {
  44. if (dispatcher == null)
  45. throw new ArgumentNullException("dispatcher");
  46. _dispatcher = dispatcher;
  47. _priority = priority;
  48. }
  49. /// <summary>
  50. /// Gets the scheduler that schedules work on the Windows.UI.Core.CoreDispatcher associated with the current Window.
  51. /// </summary>
  52. public static CoreDispatcherScheduler Current
  53. {
  54. get
  55. {
  56. var window = Window.Current;
  57. if (window == null)
  58. throw new InvalidOperationException(Strings_WindowsThreading.NO_WINDOW_CURRENT);
  59. return new CoreDispatcherScheduler(window.Dispatcher);
  60. }
  61. }
  62. /// <summary>
  63. /// Gets the Windows.UI.Core.CoreDispatcher associated with the CoreDispatcherScheduler.
  64. /// </summary>
  65. public CoreDispatcher Dispatcher
  66. {
  67. get { return _dispatcher; }
  68. }
  69. /// <summary>
  70. /// Gets the priority at which work is scheduled.
  71. /// </summary>
  72. public CoreDispatcherPriority Priority
  73. {
  74. get { return _priority; }
  75. }
  76. /// <summary>
  77. /// Schedules an action to be executed on the dispatcher.
  78. /// </summary>
  79. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  80. /// <param name="state">State passed to the action to be executed.</param>
  81. /// <param name="action">Action to be executed.</param>
  82. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  83. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  84. public override IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
  85. {
  86. if (action == null)
  87. throw new ArgumentNullException("action");
  88. var d = new SingleAssignmentDisposable();
  89. var res = _dispatcher.RunAsync(_priority, () =>
  90. {
  91. if (!d.IsDisposed)
  92. {
  93. try
  94. {
  95. d.Disposable = action(this, state);
  96. }
  97. catch (Exception ex)
  98. {
  99. //
  100. // Work-around for the behavior of throwing from RunAsync not propagating
  101. // the exception to the Application.UnhandledException event (as of W8RP)
  102. // as our users have come to expect from previous XAML stacks using Rx.
  103. //
  104. // If we wouldn't do this, there'd be an observable behavioral difference
  105. // between scheduling with TimeSpan.Zero or using this overload.
  106. //
  107. // For scheduler implementation guidance rules, see TaskPoolScheduler.cs
  108. // in System.Reactive.PlatformServices\Reactive\Concurrency.
  109. //
  110. var timer = new DispatcherTimer();
  111. timer.Interval = TimeSpan.Zero;
  112. timer.Tick += (o, e) =>
  113. {
  114. timer.Stop();
  115. ExceptionDispatchInfo.Capture(ex).Throw();
  116. };
  117. timer.Start();
  118. }
  119. }
  120. });
  121. return new CompositeDisposable(
  122. d,
  123. Disposable.Create(res.Cancel)
  124. );
  125. }
  126. /// <summary>
  127. /// Schedules an action to be executed after dueTime on the dispatcher, using a Windows.UI.Xaml.DispatcherTimer object.
  128. /// </summary>
  129. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  130. /// <param name="state">State passed to the action to be executed.</param>
  131. /// <param name="action">Action to be executed.</param>
  132. /// <param name="dueTime">Relative time after which to execute the action.</param>
  133. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  134. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  135. public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  136. {
  137. if (action == null)
  138. throw new ArgumentNullException("action");
  139. var dt = Scheduler.Normalize(dueTime);
  140. if (dt.Ticks == 0)
  141. return Schedule(state, action);
  142. var d = new MultipleAssignmentDisposable();
  143. var timer = new DispatcherTimer();
  144. timer.Tick += (o, e) =>
  145. {
  146. var t = Interlocked.Exchange(ref timer, null);
  147. if (t != null)
  148. {
  149. try
  150. {
  151. d.Disposable = action(this, state);
  152. }
  153. finally
  154. {
  155. t.Stop();
  156. action = null;
  157. }
  158. }
  159. };
  160. timer.Interval = dt;
  161. timer.Start();
  162. d.Disposable = Disposable.Create(() =>
  163. {
  164. var t = Interlocked.Exchange(ref timer, null);
  165. if (t != null)
  166. {
  167. t.Stop();
  168. action = (_, __) => Disposable.Empty;
  169. }
  170. });
  171. return d;
  172. }
  173. /// <summary>
  174. /// Schedules a periodic piece of work on the dispatcher, using a Windows.UI.Xaml.DispatcherTimer object.
  175. /// </summary>
  176. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  177. /// <param name="state">Initial state passed to the action upon the first iteration.</param>
  178. /// <param name="period">Period for running the work periodically.</param>
  179. /// <param name="action">Action to be executed, potentially updating the state.</param>
  180. /// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns>
  181. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  182. /// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than TimeSpan.Zero.</exception>
  183. public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action)
  184. {
  185. //
  186. // According to MSDN documentation, the default is TimeSpan.Zero, so that's definitely valid.
  187. // Empirical observation - negative values seem to be normalized to TimeSpan.Zero, but let's not go there.
  188. //
  189. if (period < TimeSpan.Zero)
  190. throw new ArgumentOutOfRangeException("period");
  191. if (action == null)
  192. throw new ArgumentNullException("action");
  193. var timer = new DispatcherTimer();
  194. var state1 = state;
  195. timer.Tick += (o, e) =>
  196. {
  197. state1 = action(state1);
  198. };
  199. timer.Interval = period;
  200. timer.Start();
  201. return Disposable.Create(() =>
  202. {
  203. var t = Interlocked.Exchange(ref timer, null);
  204. if (t != null)
  205. {
  206. t.Stop();
  207. action = _ => _;
  208. }
  209. });
  210. }
  211. }
  212. }
  213. #endif