ThreadPoolScheduler.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 && !NO_THREAD
  5. using System.Collections.Generic;
  6. using System.Reactive.Disposables;
  7. using System.Threading;
  8. namespace System.Reactive.Concurrency
  9. {
  10. /// <summary>
  11. /// Represents an object that schedules units of work on the CLR thread pool.
  12. /// </summary>
  13. /// <seealso cref="ThreadPoolScheduler.Instance">Singleton instance of this type exposed through this static property.</seealso>
  14. public sealed class ThreadPoolScheduler : LocalScheduler, ISchedulerLongRunning, ISchedulerPeriodic
  15. {
  16. private static readonly Lazy<ThreadPoolScheduler> s_instance = new Lazy<ThreadPoolScheduler>(() => new ThreadPoolScheduler());
  17. private static readonly Lazy<NewThreadScheduler> s_newBackgroundThread = new Lazy<NewThreadScheduler>(() => new NewThreadScheduler(action => new Thread(action) { IsBackground = true }));
  18. /// <summary>
  19. /// Gets the singleton instance of the CLR thread pool scheduler.
  20. /// </summary>
  21. public static ThreadPoolScheduler Instance => s_instance.Value;
  22. private ThreadPoolScheduler()
  23. {
  24. }
  25. /// <summary>
  26. /// Schedules an action to be executed.
  27. /// </summary>
  28. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  29. /// <param name="state">State passed to the action to be executed.</param>
  30. /// <param name="action">Action to be executed.</param>
  31. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  32. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  33. public override IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
  34. {
  35. if (action == null)
  36. throw new ArgumentNullException(nameof(action));
  37. var d = new SingleAssignmentDisposable();
  38. ThreadPool.QueueUserWorkItem(_ =>
  39. {
  40. if (!d.IsDisposed)
  41. {
  42. d.Disposable = action(this, state);
  43. }
  44. }, null);
  45. return d;
  46. }
  47. /// <summary>
  48. /// Schedules an action to be executed after dueTime, using a System.Threading.Timer object.
  49. /// </summary>
  50. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  51. /// <param name="state">State passed to the action to be executed.</param>
  52. /// <param name="action">Action to be executed.</param>
  53. /// <param name="dueTime">Relative time after which to execute the action.</param>
  54. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  55. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  56. public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  57. {
  58. if (action == null)
  59. throw new ArgumentNullException(nameof(action));
  60. var dt = Scheduler.Normalize(dueTime);
  61. if (dt.Ticks == 0)
  62. {
  63. return Schedule(state, action);
  64. }
  65. return new Timer<TState>(this, state, dt, action);
  66. }
  67. /// <summary>
  68. /// Schedules a long-running task by creating a new thread. Cancellation happens through polling.
  69. /// </summary>
  70. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  71. /// <param name="state">State passed to the action to be executed.</param>
  72. /// <param name="action">Action to be executed.</param>
  73. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  74. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  75. public IDisposable ScheduleLongRunning<TState>(TState state, Action<TState, ICancelable> action)
  76. {
  77. if (action == null)
  78. throw new ArgumentNullException(nameof(action));
  79. return s_newBackgroundThread.Value.ScheduleLongRunning(state, action);
  80. }
  81. /// <summary>
  82. /// Starts a new stopwatch object.
  83. /// </summary>
  84. /// <returns>New stopwatch object; started at the time of the request.</returns>
  85. public override IStopwatch StartStopwatch()
  86. {
  87. //
  88. // Strictly speaking, this explicit override is not necessary because the base implementation calls into
  89. // the enlightenment module to obtain the CAL, which would circle back to System.Reactive.PlatformServices
  90. // where we're currently running. This is merely a short-circuit to avoid the additional roundtrip.
  91. //
  92. return new StopwatchImpl();
  93. }
  94. /// <summary>
  95. /// Schedules a periodic piece of work, using a System.Threading.Timer object.
  96. /// </summary>
  97. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  98. /// <param name="state">Initial state passed to the action upon the first iteration.</param>
  99. /// <param name="period">Period for running the work periodically.</param>
  100. /// <param name="action">Action to be executed, potentially updating the state.</param>
  101. /// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns>
  102. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  103. /// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than zero.</exception>
  104. public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action)
  105. {
  106. if (period < TimeSpan.Zero)
  107. throw new ArgumentOutOfRangeException(nameof(period));
  108. if (action == null)
  109. throw new ArgumentNullException(nameof(action));
  110. if (period == TimeSpan.Zero)
  111. {
  112. return new FastPeriodicTimer<TState>(state, action);
  113. }
  114. else
  115. {
  116. return new PeriodicTimer<TState>(state, period, action);
  117. }
  118. }
  119. private sealed class FastPeriodicTimer<TState> : IDisposable
  120. {
  121. private TState _state;
  122. private Func<TState, TState> _action;
  123. private volatile bool _disposed;
  124. public FastPeriodicTimer(TState state, Func<TState, TState> action)
  125. {
  126. _state = state;
  127. _action = action;
  128. ThreadPool.QueueUserWorkItem(Tick, null);
  129. }
  130. private void Tick(object state)
  131. {
  132. if (!_disposed)
  133. {
  134. _state = _action(_state);
  135. ThreadPool.QueueUserWorkItem(Tick, null);
  136. }
  137. }
  138. public void Dispose()
  139. {
  140. _disposed = true;
  141. _action = Stubs<TState>.I;
  142. }
  143. }
  144. //
  145. // See ConcurrencyAbstractionLayerImpl.cs for more information about the code
  146. // below and its timer rooting behavior.
  147. //
  148. private sealed class Timer<TState> : IDisposable
  149. {
  150. private readonly MultipleAssignmentDisposable _disposable;
  151. private readonly IScheduler _parent;
  152. private readonly TState _state;
  153. private Func<IScheduler, TState, IDisposable> _action;
  154. private volatile System.Threading.Timer _timer;
  155. public Timer(IScheduler parent, TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  156. {
  157. _parent = parent;
  158. _state = state;
  159. _action = action;
  160. _disposable = new MultipleAssignmentDisposable();
  161. _disposable.Disposable = Disposable.Create(Stop);
  162. // Don't want the spin wait in Tick to get stuck if this thread gets aborted.
  163. try { }
  164. finally
  165. {
  166. //
  167. // Rooting of the timer happens through the this.Tick delegate's target object,
  168. // which is the current instance and has a field to store the Timer instance.
  169. //
  170. _timer = new System.Threading.Timer(this.Tick, null, dueTime, TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite));
  171. }
  172. }
  173. private void Tick(object state)
  174. {
  175. try
  176. {
  177. _disposable.Disposable = _action(_parent, _state);
  178. }
  179. finally
  180. {
  181. SpinWait.SpinUntil(IsTimerAssigned);
  182. Stop();
  183. }
  184. }
  185. private bool IsTimerAssigned() => _timer != null;
  186. public void Dispose() => _disposable.Dispose();
  187. private void Stop()
  188. {
  189. var timer = _timer;
  190. if (timer != TimerStubs.Never)
  191. {
  192. _action = Nop;
  193. _timer = TimerStubs.Never;
  194. timer.Dispose();
  195. }
  196. }
  197. private IDisposable Nop(IScheduler scheduler, TState state) => Disposable.Empty;
  198. }
  199. private sealed class PeriodicTimer<TState> : IDisposable
  200. {
  201. private TState _state;
  202. private Func<TState, TState> _action;
  203. private readonly AsyncLock _gate;
  204. private volatile System.Threading.Timer _timer;
  205. public PeriodicTimer(TState state, TimeSpan period, Func<TState, TState> action)
  206. {
  207. _state = state;
  208. _action = action;
  209. _gate = new AsyncLock();
  210. //
  211. // Rooting of the timer happens through the this.Tick delegate's target object,
  212. // which is the current instance and has a field to store the Timer instance.
  213. //
  214. _timer = new System.Threading.Timer(this.Tick, null, period, period);
  215. }
  216. private void Tick(object state)
  217. {
  218. _gate.Wait(() =>
  219. {
  220. _state = _action(_state);
  221. });
  222. }
  223. public void Dispose()
  224. {
  225. var timer = _timer;
  226. if (timer != null)
  227. {
  228. _action = Stubs<TState>.I;
  229. _timer = null;
  230. timer.Dispose();
  231. _gate.Dispose();
  232. }
  233. }
  234. }
  235. }
  236. }
  237. #endif