1
0

ThreadPoolScheduler.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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. #if !NO_STOPWATCH
  84. /// <summary>
  85. /// Starts a new stopwatch object.
  86. /// </summary>
  87. /// <returns>New stopwatch object; started at the time of the request.</returns>
  88. public override IStopwatch StartStopwatch()
  89. {
  90. //
  91. // Strictly speaking, this explicit override is not necessary because the base implementation calls into
  92. // the enlightenment module to obtain the CAL, which would circle back to System.Reactive.PlatformServices
  93. // where we're currently running. This is merely a short-circuit to avoid the additional roundtrip.
  94. //
  95. return new StopwatchImpl();
  96. }
  97. #endif
  98. /// <summary>
  99. /// Schedules a periodic piece of work, using a System.Threading.Timer object.
  100. /// </summary>
  101. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  102. /// <param name="state">Initial state passed to the action upon the first iteration.</param>
  103. /// <param name="period">Period for running the work periodically.</param>
  104. /// <param name="action">Action to be executed, potentially updating the state.</param>
  105. /// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns>
  106. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  107. /// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than zero.</exception>
  108. public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action)
  109. {
  110. if (period < TimeSpan.Zero)
  111. throw new ArgumentOutOfRangeException(nameof(period));
  112. if (action == null)
  113. throw new ArgumentNullException(nameof(action));
  114. if (period == TimeSpan.Zero)
  115. {
  116. return new FastPeriodicTimer<TState>(state, action);
  117. }
  118. else
  119. {
  120. return new PeriodicTimer<TState>(state, period, action);
  121. }
  122. }
  123. sealed class FastPeriodicTimer<TState> : IDisposable
  124. {
  125. private TState _state;
  126. private Func<TState, TState> _action;
  127. private volatile bool _disposed;
  128. public FastPeriodicTimer(TState state, Func<TState, TState> action)
  129. {
  130. _state = state;
  131. _action = action;
  132. ThreadPool.QueueUserWorkItem(Tick, null);
  133. }
  134. private void Tick(object state)
  135. {
  136. if (!_disposed)
  137. {
  138. _state = _action(_state);
  139. ThreadPool.QueueUserWorkItem(Tick, null);
  140. }
  141. }
  142. public void Dispose()
  143. {
  144. _disposed = true;
  145. _action = Stubs<TState>.I;
  146. }
  147. }
  148. #if USE_TIMER_SELF_ROOT
  149. //
  150. // See ConcurrencyAbstractionLayerImpl.cs for more information about the code
  151. // below and its timer rooting behavior.
  152. //
  153. sealed class Timer<TState> : IDisposable
  154. {
  155. private readonly MultipleAssignmentDisposable _disposable;
  156. private readonly IScheduler _parent;
  157. private readonly TState _state;
  158. private Func<IScheduler, TState, IDisposable> _action;
  159. private volatile System.Threading.Timer _timer;
  160. public Timer(IScheduler parent, TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  161. {
  162. _parent = parent;
  163. _state = state;
  164. _action = action;
  165. _disposable = new MultipleAssignmentDisposable();
  166. _disposable.Disposable = Disposable.Create(Stop);
  167. // Don't want the spin wait in Tick to get stuck if this thread gets aborted.
  168. try { }
  169. finally
  170. {
  171. //
  172. // Rooting of the timer happens through the this.Tick delegate's target object,
  173. // which is the current instance and has a field to store the Timer instance.
  174. //
  175. _timer = new System.Threading.Timer(this.Tick, null, dueTime, TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite));
  176. }
  177. }
  178. private void Tick(object state)
  179. {
  180. try
  181. {
  182. _disposable.Disposable = _action(_parent, _state);
  183. }
  184. finally
  185. {
  186. SpinWait.SpinUntil(IsTimerAssigned);
  187. Stop();
  188. }
  189. }
  190. private bool IsTimerAssigned()
  191. {
  192. return _timer != null;
  193. }
  194. public void Dispose()
  195. {
  196. _disposable.Dispose();
  197. }
  198. private void Stop()
  199. {
  200. var timer = _timer;
  201. if (timer != TimerStubs.Never)
  202. {
  203. _action = Nop;
  204. _timer = TimerStubs.Never;
  205. timer.Dispose();
  206. }
  207. }
  208. private IDisposable Nop(IScheduler scheduler, TState state)
  209. {
  210. return Disposable.Empty;
  211. }
  212. }
  213. sealed class PeriodicTimer<TState> : IDisposable
  214. {
  215. private TState _state;
  216. private Func<TState, TState> _action;
  217. private readonly AsyncLock _gate;
  218. private volatile System.Threading.Timer _timer;
  219. public PeriodicTimer(TState state, TimeSpan period, Func<TState, TState> action)
  220. {
  221. _state = state;
  222. _action = action;
  223. _gate = new AsyncLock();
  224. //
  225. // Rooting of the timer happens through the this.Tick delegate's target object,
  226. // which is the current instance and has a field to store the Timer instance.
  227. //
  228. _timer = new System.Threading.Timer(this.Tick, null, period, period);
  229. }
  230. private void Tick(object state)
  231. {
  232. _gate.Wait(() =>
  233. {
  234. _state = _action(_state);
  235. });
  236. }
  237. public void Dispose()
  238. {
  239. var timer = _timer;
  240. if (timer != null)
  241. {
  242. _action = Stubs<TState>.I;
  243. _timer = null;
  244. timer.Dispose();
  245. _gate.Dispose();
  246. }
  247. }
  248. }
  249. #else
  250. abstract class Timer
  251. {
  252. //
  253. // Note: the dictionary exists to "root" the timers so that they are not garbage collected and finalized while they are running.
  254. //
  255. protected static readonly HashSet<System.Threading.Timer> s_timers = new HashSet<System.Threading.Timer>();
  256. }
  257. sealed class Timer<TState> : Timer, IDisposable
  258. {
  259. private readonly MultipleAssignmentDisposable _disposable;
  260. private readonly IScheduler _parent;
  261. private readonly TState _state;
  262. private Func<IScheduler, TState, IDisposable> _action;
  263. private System.Threading.Timer _timer;
  264. private bool _hasAdded;
  265. private bool _hasRemoved;
  266. public Timer(IScheduler parent, TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  267. {
  268. _disposable = new MultipleAssignmentDisposable();
  269. _disposable.Disposable = Disposable.Create(Unroot);
  270. _parent = parent;
  271. _state = state;
  272. _action = action;
  273. _timer = new System.Threading.Timer(Tick, null, dueTime, TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite));
  274. lock (s_timers)
  275. {
  276. if (!_hasRemoved)
  277. {
  278. s_timers.Add(_timer);
  279. _hasAdded = true;
  280. }
  281. }
  282. }
  283. private void Tick(object state)
  284. {
  285. try
  286. {
  287. _disposable.Disposable = _action(_parent, _state);
  288. }
  289. finally
  290. {
  291. Unroot();
  292. }
  293. }
  294. private void Unroot()
  295. {
  296. _action = Nop;
  297. var timer = default(System.Threading.Timer);
  298. lock (s_timers)
  299. {
  300. if (!_hasRemoved)
  301. {
  302. timer = _timer;
  303. _timer = null;
  304. if (_hasAdded && timer != null)
  305. s_timers.Remove(timer);
  306. _hasRemoved = true;
  307. }
  308. }
  309. if (timer != null)
  310. timer.Dispose();
  311. }
  312. private IDisposable Nop(IScheduler scheduler, TState state)
  313. {
  314. return Disposable.Empty;
  315. }
  316. public void Dispose()
  317. {
  318. _disposable.Dispose();
  319. }
  320. }
  321. abstract class PeriodicTimer
  322. {
  323. //
  324. // Note: the dictionary exists to "root" the timers so that they are not garbage collected and finalized while they are running.
  325. //
  326. protected static readonly HashSet<System.Threading.Timer> s_timers = new HashSet<System.Threading.Timer>();
  327. }
  328. sealed class PeriodicTimer<TState> : PeriodicTimer, IDisposable
  329. {
  330. private readonly AsyncLock _gate;
  331. private TState _state;
  332. private Func<TState, TState> _action;
  333. private System.Threading.Timer _timer;
  334. public PeriodicTimer(TState state, TimeSpan period, Func<TState, TState> action)
  335. {
  336. _gate = new AsyncLock();
  337. _state = state;
  338. _action = action;
  339. _timer = new System.Threading.Timer(Tick, null, period, period);
  340. lock (s_timers)
  341. {
  342. s_timers.Add(_timer);
  343. }
  344. }
  345. private void Tick(object state)
  346. {
  347. _gate.Wait(() =>
  348. {
  349. _state = _action(_state);
  350. });
  351. }
  352. public void Dispose()
  353. {
  354. var timer = default(System.Threading.Timer);
  355. lock (s_timers)
  356. {
  357. timer = _timer;
  358. _timer = null;
  359. if (timer != null)
  360. s_timers.Remove(timer);
  361. }
  362. if (timer != null)
  363. {
  364. timer.Dispose();
  365. _gate.Dispose();
  366. _action = Stubs<TState>.I;
  367. }
  368. }
  369. }
  370. #endif
  371. }
  372. }
  373. #endif