CoreDispatcherScheduler.cs 9.8 KB

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