ThreadPoolScheduler.cs 11 KB

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