TaskPoolScheduler.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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 Lazy<TaskPoolScheduler> s_instance = new Lazy<TaskPoolScheduler>(() => 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.Value;
  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. TaskHelpers.Delay(dueTime, ct.Token).ContinueWith(_ =>
  103. {
  104. if (!d.IsDisposed)
  105. d.Disposable = action(this, state);
  106. }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion, taskFactory.Scheduler);
  107. return d;
  108. #else
  109. return DefaultScheduler.Instance.Schedule(state, dt, (_, state1) => Schedule(state1, action));
  110. #endif
  111. }
  112. /// <summary>
  113. /// Schedules a long-running task by creating a new task using TaskCreationOptions.LongRunning. Cancellation happens through polling.
  114. /// </summary>
  115. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  116. /// <param name="state">State passed to the action to be executed.</param>
  117. /// <param name="action">Action to be executed.</param>
  118. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  119. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  120. public IDisposable ScheduleLongRunning<TState>(TState state, Action<TState, ICancelable> action)
  121. {
  122. var d = new BooleanDisposable();
  123. taskFactory.StartNew(() =>
  124. {
  125. //
  126. // Notice we don't check d.IsDisposed. The contract for ISchedulerLongRunning
  127. // requires us to ensure the scheduled work gets an opportunity to observe
  128. // the cancellation request.
  129. //
  130. action(state, d);
  131. }, TaskCreationOptions.LongRunning);
  132. return d;
  133. }
  134. #if !NO_STOPWATCH
  135. /// <summary>
  136. /// Gets a new stopwatch ob ject.
  137. /// </summary>
  138. /// <returns>New stopwatch object; started at the time of the request.</returns>
  139. public override IStopwatch StartStopwatch()
  140. {
  141. //
  142. // Strictly speaking, this explicit override is not necessary because the base implementation calls into
  143. // the enlightenment module to obtain the CAL, which would circle back to System.Reactive.PlatformServices
  144. // where we're currently running. This is merely a short-circuit to avoid the additional roundtrip.
  145. //
  146. return new StopwatchImpl();
  147. }
  148. #endif
  149. /// <summary>
  150. /// Schedules a periodic piece of work by running a platform-specific timer to create tasks periodically.
  151. /// </summary>
  152. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  153. /// <param name="state">Initial state passed to the action upon the first iteration.</param>
  154. /// <param name="period">Period for running the work periodically.</param>
  155. /// <param name="action">Action to be executed, potentially updating the state.</param>
  156. /// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns>
  157. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  158. /// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than TimeSpan.Zero.</exception>
  159. public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action)
  160. {
  161. if (period < TimeSpan.Zero)
  162. throw new ArgumentOutOfRangeException("period");
  163. if (action == null)
  164. throw new ArgumentNullException("action");
  165. #if !NO_TASK_DELAY
  166. var cancel = new CancellationDisposable();
  167. var state1 = state;
  168. var gate = new AsyncLock();
  169. var moveNext = default(Action);
  170. moveNext = () =>
  171. {
  172. TaskHelpers.Delay(period, cancel.Token).ContinueWith(
  173. _ =>
  174. {
  175. moveNext();
  176. gate.Wait(() =>
  177. {
  178. state1 = action(state1);
  179. });
  180. },
  181. CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion, taskFactory.Scheduler
  182. );
  183. };
  184. moveNext();
  185. return StableCompositeDisposable.Create(cancel, gate);
  186. #else
  187. var state1 = state;
  188. var gate = new AsyncLock();
  189. var timer = ConcurrencyAbstractionLayer.Current.StartPeriodicTimer(() =>
  190. {
  191. taskFactory.StartNew(() =>
  192. {
  193. gate.Wait(() =>
  194. {
  195. state1 = action(state1);
  196. });
  197. });
  198. }, period);
  199. return StableCompositeDisposable.Create(timer, gate);
  200. #endif
  201. }
  202. }
  203. }
  204. #endif