ThreadPoolScheduler.cs 11 KB

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