TaskPoolScheduler.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Reactive.Disposables;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace System.Reactive.Concurrency
  8. {
  9. /// <summary>
  10. /// Represents an object that schedules units of work on the Task Parallel Library (TPL) task pool.
  11. /// </summary>
  12. /// <seealso cref="Default">Instance of this type using the default TaskScheduler to schedule work on the TPL task pool.</seealso>
  13. public sealed class TaskPoolScheduler : LocalScheduler, ISchedulerLongRunning, ISchedulerPeriodic
  14. {
  15. private sealed class ScheduledWorkItem<TState> : IDisposable
  16. {
  17. private readonly TState _state;
  18. private readonly TaskPoolScheduler _scheduler;
  19. private readonly Func<IScheduler, TState, IDisposable> _action;
  20. private SerialDisposableValue _cancel;
  21. public ScheduledWorkItem(TaskPoolScheduler scheduler, TState state, Func<IScheduler, TState, IDisposable> action)
  22. {
  23. _state = state;
  24. _action = action;
  25. _scheduler = scheduler;
  26. var cancelable = new CancellationDisposable();
  27. _cancel.Disposable = cancelable;
  28. scheduler._taskFactory.StartNew(
  29. thisObject =>
  30. {
  31. var @this = (ScheduledWorkItem<TState>)thisObject!;
  32. //
  33. // BREAKING CHANGE v2.0 > v1.x - No longer escalating exceptions using a throwing
  34. // helper thread.
  35. //
  36. // Our manual escalation based on the creation of a throwing thread was merely to
  37. // expedite the process of throwing the exception that would otherwise occur on the
  38. // finalizer thread at a later point during the app's lifetime.
  39. //
  40. // However, it also prevented applications from observing the exception through
  41. // the TaskScheduler.UnobservedTaskException static event. Also, starting form .NET
  42. // 4.5, the default behavior of the task pool is not to take down the application
  43. // when an exception goes unobserved (done as part of the async/await work). It'd
  44. // be weird for Rx not to follow the platform defaults.
  45. //
  46. // General implementation guidelines for schedulers (in order of importance):
  47. //
  48. // 1. Always thunk through to the underlying infrastructure with a wrapper that's as tiny as possible.
  49. // 2. Global exception notification/handling mechanisms shouldn't be bypassed.
  50. // 3. Escalation behavior for exceptions is left to the underlying infrastructure.
  51. //
  52. // The Catch extension method for IScheduler (added earlier) allows to re-route
  53. // exceptions at stage 2. If the exception isn't handled at the Rx level, it
  54. // propagates by means of a rethrow, falling back to behavior in 3.
  55. //
  56. @this._cancel.Disposable = @this._action(@this._scheduler, @this._state);
  57. },
  58. this,
  59. cancelable.Token);
  60. }
  61. public void Dispose()
  62. {
  63. _cancel.Dispose();
  64. }
  65. }
  66. private sealed class SlowlyScheduledWorkItem<TState> : IDisposable
  67. {
  68. private readonly TState _state;
  69. private readonly TaskPoolScheduler _scheduler;
  70. private readonly Func<IScheduler, TState, IDisposable> _action;
  71. private MultipleAssignmentDisposableValue _cancel;
  72. public SlowlyScheduledWorkItem(TaskPoolScheduler scheduler, TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  73. {
  74. _state = state;
  75. _action = action;
  76. _scheduler = scheduler;
  77. var ct = new CancellationDisposable();
  78. _cancel.Disposable = ct;
  79. TaskHelpers.Delay(dueTime, ct.Token).ContinueWith(
  80. (_, thisObject) =>
  81. {
  82. var @this = (SlowlyScheduledWorkItem<TState>)thisObject!;
  83. if (!@this._cancel.IsDisposed)
  84. {
  85. @this._cancel.Disposable = @this._action(@this._scheduler, @this._state);
  86. }
  87. },
  88. this,
  89. CancellationToken.None,
  90. TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion,
  91. scheduler._taskFactory.Scheduler ?? TaskScheduler.Default);
  92. }
  93. public void Dispose()
  94. {
  95. _cancel.Dispose();
  96. }
  97. }
  98. private sealed class LongScheduledWorkItem<TState> : ICancelable
  99. {
  100. private readonly TState _state;
  101. private readonly Action<TState, ICancelable> _action;
  102. private IDisposable? _cancel;
  103. public LongScheduledWorkItem(TaskPoolScheduler scheduler, TState state, Action<TState, ICancelable> action)
  104. {
  105. _state = state;
  106. _action = action;
  107. scheduler._taskFactory.StartNew(
  108. thisObject =>
  109. {
  110. var @this = (LongScheduledWorkItem<TState>)thisObject!;
  111. //
  112. // Notice we don't check _cancel.IsDisposed. The contract for ISchedulerLongRunning
  113. // requires us to ensure the scheduled work gets an opportunity to observe
  114. // the cancellation request.
  115. //
  116. @this._action(@this._state, @this);
  117. },
  118. this,
  119. TaskCreationOptions.LongRunning);
  120. }
  121. public void Dispose()
  122. {
  123. Disposable.Dispose(ref _cancel);
  124. }
  125. public bool IsDisposed => Disposable.GetIsDisposed(ref _cancel);
  126. }
  127. private static readonly Lazy<TaskPoolScheduler> LazyInstance = new Lazy<TaskPoolScheduler>(static () => new TaskPoolScheduler(new TaskFactory(TaskScheduler.Default)));
  128. private readonly TaskFactory _taskFactory;
  129. /// <summary>
  130. /// Creates an object that schedules units of work using the provided <see cref="TaskFactory"/>.
  131. /// </summary>
  132. /// <param name="taskFactory">Task factory used to create tasks to run units of work.</param>
  133. /// <exception cref="ArgumentNullException"><paramref name="taskFactory"/> is <c>null</c>.</exception>
  134. public TaskPoolScheduler(TaskFactory taskFactory)
  135. {
  136. _taskFactory = taskFactory ?? throw new ArgumentNullException(nameof(taskFactory));
  137. }
  138. /// <summary>
  139. /// Gets an instance of this scheduler that uses the default <see cref="TaskScheduler"/>.
  140. /// </summary>
  141. public static TaskPoolScheduler Default => LazyInstance.Value;
  142. /// <summary>
  143. /// Schedules an action to be executed.
  144. /// </summary>
  145. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  146. /// <param name="state">State passed to the action to be executed.</param>
  147. /// <param name="action">Action to be executed.</param>
  148. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  149. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  150. public override IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
  151. {
  152. if (action == null)
  153. {
  154. throw new ArgumentNullException(nameof(action));
  155. }
  156. return new ScheduledWorkItem<TState>(this, state, action);
  157. }
  158. /// <summary>
  159. /// Schedules an action to be executed after dueTime.
  160. /// </summary>
  161. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  162. /// <param name="state">State passed to the action to be executed.</param>
  163. /// <param name="action">Action to be executed.</param>
  164. /// <param name="dueTime">Relative time after which to execute the action.</param>
  165. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  166. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  167. public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  168. {
  169. if (action == null)
  170. {
  171. throw new ArgumentNullException(nameof(action));
  172. }
  173. var dt = Scheduler.Normalize(dueTime);
  174. if (dt.Ticks == 0)
  175. {
  176. return Schedule(state, action);
  177. }
  178. return ScheduleSlow(state, dt, action);
  179. }
  180. private IDisposable ScheduleSlow<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  181. {
  182. return new SlowlyScheduledWorkItem<TState>(this, state, dueTime, action);
  183. }
  184. /// <summary>
  185. /// Schedules a long-running task by creating a new task using TaskCreationOptions.LongRunning. Cancellation happens through polling.
  186. /// </summary>
  187. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  188. /// <param name="state">State passed to the action to be executed.</param>
  189. /// <param name="action">Action to be executed.</param>
  190. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  191. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  192. public IDisposable ScheduleLongRunning<TState>(TState state, Action<TState, ICancelable> action)
  193. {
  194. return new LongScheduledWorkItem<TState>(this, state, action);
  195. }
  196. /// <summary>
  197. /// Gets a new stopwatch object.
  198. /// </summary>
  199. /// <returns>New stopwatch object; started at the time of the request.</returns>
  200. public override IStopwatch StartStopwatch()
  201. {
  202. //
  203. // Strictly speaking, this explicit override is not necessary because the base implementation calls into
  204. // the enlightenment module to obtain the CAL, which would circle back to System.Reactive.PlatformServices
  205. // where we're currently running. This is merely a short-circuit to avoid the additional roundtrip.
  206. //
  207. return new StopwatchImpl();
  208. }
  209. /// <summary>
  210. /// Schedules a periodic piece of work by running a platform-specific timer to create tasks periodically.
  211. /// </summary>
  212. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  213. /// <param name="state">Initial state passed to the action upon the first iteration.</param>
  214. /// <param name="period">Period for running the work periodically.</param>
  215. /// <param name="action">Action to be executed, potentially updating the state.</param>
  216. /// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns>
  217. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  218. /// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than <see cref="TimeSpan.Zero"/>.</exception>
  219. public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action)
  220. {
  221. if (period < TimeSpan.Zero)
  222. {
  223. throw new ArgumentOutOfRangeException(nameof(period));
  224. }
  225. if (action == null)
  226. {
  227. throw new ArgumentNullException(nameof(action));
  228. }
  229. return new PeriodicallyScheduledWorkItem<TState>(state, period, action, _taskFactory);
  230. }
  231. private sealed class PeriodicallyScheduledWorkItem<TState> : IDisposable
  232. {
  233. private TState _state;
  234. private readonly TimeSpan _period;
  235. private readonly TaskFactory _taskFactory;
  236. private readonly Func<TState, TState> _action;
  237. private readonly AsyncLock _gate = new AsyncLock();
  238. private readonly CancellationTokenSource _cts = new CancellationTokenSource();
  239. public PeriodicallyScheduledWorkItem(TState state, TimeSpan period, Func<TState, TState> action, TaskFactory taskFactory)
  240. {
  241. _state = state;
  242. _period = period;
  243. _action = action;
  244. _taskFactory = taskFactory;
  245. MoveNext();
  246. }
  247. public void Dispose()
  248. {
  249. _cts.Cancel();
  250. _gate.Dispose();
  251. }
  252. private void MoveNext()
  253. {
  254. TaskHelpers.Delay(_period, _cts.Token).ContinueWith(
  255. static (_, thisObject) =>
  256. {
  257. var @this = (PeriodicallyScheduledWorkItem<TState>)thisObject!;
  258. @this.MoveNext();
  259. @this._gate.Wait(
  260. @this,
  261. static closureThis => closureThis._state = closureThis._action(closureThis._state));
  262. },
  263. this,
  264. CancellationToken.None,
  265. TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion,
  266. _taskFactory.Scheduler ?? TaskScheduler.Default
  267. );
  268. }
  269. }
  270. }
  271. }