TaskPoolScheduler.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. #if !NO_TPL
  3. using System.Reactive.Disposables;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. namespace System.Reactive.Concurrency
  7. {
  8. /// <summary>
  9. /// Represents an object that schedules units of work on the Task Parallel Library (TPL) task pool.
  10. /// </summary>
  11. /// <seealso cref="TaskPoolScheduler.Default">Instance of this type using the default TaskScheduler to schedule work on the TPL task pool.</seealso>
  12. public sealed class TaskPoolScheduler : LocalScheduler, ISchedulerLongRunning, ISchedulerPeriodic
  13. {
  14. private static readonly TaskPoolScheduler s_instance = new TaskPoolScheduler(new TaskFactory(TaskScheduler.Default));
  15. private readonly TaskFactory taskFactory;
  16. /// <summary>
  17. /// Creates an object that schedules units of work using the provided TaskFactory.
  18. /// </summary>
  19. /// <param name="taskFactory">Task factory used to create tasks to run units of work.</param>
  20. /// <exception cref="ArgumentNullException"><paramref name="taskFactory"/> is null.</exception>
  21. public TaskPoolScheduler(TaskFactory taskFactory)
  22. {
  23. if (taskFactory == null)
  24. throw new ArgumentNullException("taskFactory");
  25. this.taskFactory = taskFactory;
  26. }
  27. /// <summary>
  28. /// Gets an instance of this scheduler that uses the default TaskScheduler.
  29. /// </summary>
  30. public static TaskPoolScheduler Default
  31. {
  32. get
  33. {
  34. return s_instance;
  35. }
  36. }
  37. /// <summary>
  38. /// Schedules an action to be executed.
  39. /// </summary>
  40. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  41. /// <param name="state">State passed to the action to be executed.</param>
  42. /// <param name="action">Action to be executed.</param>
  43. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  44. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  45. public override IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
  46. {
  47. if (action == null)
  48. throw new ArgumentNullException("action");
  49. var d = new SerialDisposable();
  50. var cancelable = new CancellationDisposable();
  51. d.Disposable = cancelable;
  52. taskFactory.StartNew(() =>
  53. {
  54. //
  55. // BREAKING CHANGE v2.0 > v1.x - No longer escalating exceptions using a throwing
  56. // helper thread.
  57. //
  58. // Our manual escalation based on the creation of a throwing thread was merely to
  59. // expedite the process of throwing the exception that would otherwise occur on the
  60. // finalizer thread at a later point during the app's lifetime.
  61. //
  62. // However, it also prevented applications from observing the exception through
  63. // the TaskScheduler.UnobservedTaskException static event. Also, starting form .NET
  64. // 4.5, the default behavior of the task pool is not to take down the application
  65. // when an exception goes unobserved (done as part of the async/await work). It'd
  66. // be weird for Rx not to follow the platform defaults.
  67. //
  68. // General implementation guidelines for schedulers (in order of importance):
  69. //
  70. // 1. Always thunk through to the underlying infrastructure with a wrapper that's as tiny as possible.
  71. // 2. Global exception notification/handling mechanisms shouldn't be bypassed.
  72. // 3. Escalation behavior for exceptions is left to the underlying infrastructure.
  73. //
  74. // The Catch extension method for IScheduler (added earlier) allows to re-route
  75. // exceptions at stage 2. If the exception isn't handled at the Rx level, it
  76. // propagates by means of a rethrow, falling back to behavior in 3.
  77. //
  78. d.Disposable = action(this, state);
  79. }, cancelable.Token);
  80. return d;
  81. }
  82. /// <summary>
  83. /// Schedules an action to be executed after dueTime.
  84. /// </summary>
  85. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  86. /// <param name="state">State passed to the action to be executed.</param>
  87. /// <param name="action">Action to be executed.</param>
  88. /// <param name="dueTime">Relative time after which to execute the action.</param>
  89. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  90. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  91. public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  92. {
  93. if (action == null)
  94. throw new ArgumentNullException("action");
  95. var dt = Scheduler.Normalize(dueTime);
  96. if (dt.Ticks == 0)
  97. return Schedule(state, action);
  98. #if !NO_TASK_DELAY
  99. var d = new MultipleAssignmentDisposable();
  100. var ct = new CancellationDisposable();
  101. d.Disposable = ct;
  102. #if USE_TASKEX
  103. TaskEx.Delay(dueTime, ct.Token).ContinueWith(_ =>
  104. #else
  105. Task.Delay(dueTime, ct.Token).ContinueWith(_ =>
  106. #endif
  107. {
  108. if (!d.IsDisposed)
  109. d.Disposable = action(this, state);
  110. }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion, taskFactory.Scheduler);
  111. return d;
  112. #else
  113. return DefaultScheduler.Instance.Schedule(state, dt, (_, state1) => Schedule(state1, action));
  114. #endif
  115. }
  116. /// <summary>
  117. /// Schedules a long-running task by creating a new task using TaskCreationOptions.LongRunning. Cancellation happens through polling.
  118. /// </summary>
  119. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  120. /// <param name="state">State passed to the action to be executed.</param>
  121. /// <param name="action">Action to be executed.</param>
  122. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  123. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  124. public IDisposable ScheduleLongRunning<TState>(TState state, Action<TState, ICancelable> action)
  125. {
  126. var d = new BooleanDisposable();
  127. taskFactory.StartNew(() =>
  128. {
  129. //
  130. // Notice we don't check d.IsDisposed. The contract for ISchedulerLongRunning
  131. // requires us to ensure the scheduled work gets an opportunity to observe
  132. // the cancellation request.
  133. //
  134. action(state, d);
  135. }, TaskCreationOptions.LongRunning);
  136. return d;
  137. }
  138. #if !NO_STOPWATCH
  139. /// <summary>
  140. /// Gets a new stopwatch ob ject.
  141. /// </summary>
  142. /// <returns>New stopwatch object; started at the time of the request.</returns>
  143. public override IStopwatch StartStopwatch()
  144. {
  145. //
  146. // Strictly speaking, this explicit override is not necessary because the base implementation calls into
  147. // the enlightenment module to obtain the CAL, which would circle back to System.Reactive.PlatformServices
  148. // where we're currently running. This is merely a short-circuit to avoid the additional roundtrip.
  149. //
  150. return new StopwatchImpl();
  151. }
  152. #endif
  153. /// <summary>
  154. /// Schedules a periodic piece of work by running a platform-specific timer to create tasks periodically.
  155. /// </summary>
  156. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  157. /// <param name="state">Initial state passed to the action upon the first iteration.</param>
  158. /// <param name="period">Period for running the work periodically.</param>
  159. /// <param name="action">Action to be executed, potentially updating the state.</param>
  160. /// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns>
  161. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  162. /// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than TimeSpan.Zero.</exception>
  163. public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action)
  164. {
  165. if (period < TimeSpan.Zero)
  166. throw new ArgumentOutOfRangeException("period");
  167. if (action == null)
  168. throw new ArgumentNullException("action");
  169. #if !NO_TASK_DELAY
  170. var cancel = new CancellationDisposable();
  171. var state1 = state;
  172. var gate = new AsyncLock();
  173. var moveNext = default(Action);
  174. moveNext = () =>
  175. {
  176. #if USE_TASKEX
  177. TaskEx.Delay(period, cancel.Token).ContinueWith(
  178. #else
  179. Task.Delay(period, cancel.Token).ContinueWith(
  180. #endif
  181. _ =>
  182. {
  183. moveNext();
  184. gate.Wait(() =>
  185. {
  186. state1 = action(state1);
  187. });
  188. },
  189. CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion, taskFactory.Scheduler
  190. );
  191. };
  192. moveNext();
  193. return new CompositeDisposable(cancel, gate);
  194. #else
  195. var state1 = state;
  196. var gate = new AsyncLock();
  197. var timer = ConcurrencyAbstractionLayer.Current.StartPeriodicTimer(() =>
  198. {
  199. taskFactory.StartNew(() =>
  200. {
  201. gate.Wait(() =>
  202. {
  203. state1 = action(state1);
  204. });
  205. });
  206. }, period);
  207. return new CompositeDisposable(timer, gate);
  208. #endif
  209. }
  210. }
  211. }
  212. #endif