1
0

ThreadPoolScheduler.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. #if !WINDOWS && !NO_THREAD
  3. using System.Collections.Generic;
  4. using System.Reactive.Disposables;
  5. using System.Threading;
  6. namespace System.Reactive.Concurrency
  7. {
  8. /// <summary>
  9. /// Represents an object that schedules units of work on the CLR thread pool.
  10. /// </summary>
  11. /// <seealso cref="ThreadPoolScheduler.Instance">Singleton instance of this type exposed through this static property.</seealso>
  12. public sealed class ThreadPoolScheduler : LocalScheduler, ISchedulerLongRunning, ISchedulerPeriodic
  13. {
  14. private static readonly Lazy<ThreadPoolScheduler> s_instance = new Lazy<ThreadPoolScheduler>(() => new ThreadPoolScheduler());
  15. private static readonly Lazy<NewThreadScheduler> s_newBackgroundThread = new Lazy<NewThreadScheduler>(() => new NewThreadScheduler(action => new Thread(action) { IsBackground = true }));
  16. /// <summary>
  17. /// Gets the singleton instance of the CLR thread pool scheduler.
  18. /// </summary>
  19. public static ThreadPoolScheduler Instance
  20. {
  21. get
  22. {
  23. return s_instance.Value;
  24. }
  25. }
  26. ThreadPoolScheduler()
  27. {
  28. }
  29. /// <summary>
  30. /// Schedules an action to be executed.
  31. /// </summary>
  32. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  33. /// <param name="state">State passed to the action to be executed.</param>
  34. /// <param name="action">Action to be executed.</param>
  35. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  36. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  37. public override IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
  38. {
  39. if (action == null)
  40. throw new ArgumentNullException("action");
  41. var d = new SingleAssignmentDisposable();
  42. ThreadPool.QueueUserWorkItem(_ =>
  43. {
  44. if (!d.IsDisposed)
  45. d.Disposable = action(this, state);
  46. }, null);
  47. return d;
  48. }
  49. /// <summary>
  50. /// Schedules an action to be executed after dueTime, using a System.Threading.Timer object.
  51. /// </summary>
  52. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  53. /// <param name="state">State passed to the action to be executed.</param>
  54. /// <param name="action">Action to be executed.</param>
  55. /// <param name="dueTime">Relative time after which to execute the action.</param>
  56. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  57. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  58. public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  59. {
  60. if (action == null)
  61. throw new ArgumentNullException("action");
  62. var dt = Scheduler.Normalize(dueTime);
  63. if (dt.Ticks == 0)
  64. return Schedule(state, action);
  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 null.</exception>
  75. public IDisposable ScheduleLongRunning<TState>(TState state, Action<TState, ICancelable> action)
  76. {
  77. if (action == null)
  78. throw new ArgumentNullException("action");
  79. return s_newBackgroundThread.Value.ScheduleLongRunning(state, action);
  80. }
  81. #if !NO_STOPWATCH
  82. /// <summary>
  83. /// Starts a new stopwatch object.
  84. /// </summary>
  85. /// <returns>New stopwatch object; started at the time of the request.</returns>
  86. public override IStopwatch StartStopwatch()
  87. {
  88. //
  89. // Strictly speaking, this explicit override is not necessary because the base implementation calls into
  90. // the enlightenment module to obtain the CAL, which would circle back to System.Reactive.PlatformServices
  91. // where we're currently running. This is merely a short-circuit to avoid the additional roundtrip.
  92. //
  93. return new StopwatchImpl();
  94. }
  95. #endif
  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("period");
  110. if (action == null)
  111. throw new ArgumentNullException("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. #if USE_TIMER_SELF_ROOT
  147. //
  148. // See ConcurrencyAbstractionLayerImpl.cs for more information about the code
  149. // below and its timer rooting behavior.
  150. //
  151. sealed class Timer<TState> : IDisposable
  152. {
  153. private readonly MultipleAssignmentDisposable _disposable;
  154. private readonly IScheduler _parent;
  155. private readonly TState _state;
  156. private Func<IScheduler, TState, IDisposable> _action;
  157. private volatile System.Threading.Timer _timer;
  158. public Timer(IScheduler parent, TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  159. {
  160. _parent = parent;
  161. _state = state;
  162. _action = action;
  163. _disposable = new MultipleAssignmentDisposable();
  164. _disposable.Disposable = Disposable.Create(Stop);
  165. // Don't want the spin wait in Tick to get stuck if this thread gets aborted.
  166. try { }
  167. finally
  168. {
  169. //
  170. // Rooting of the timer happens through the this.Tick delegate's target object,
  171. // which is the current instance and has a field to store the Timer instance.
  172. //
  173. _timer = new System.Threading.Timer(this.Tick, null, dueTime, TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite));
  174. }
  175. }
  176. private void Tick(object state)
  177. {
  178. try
  179. {
  180. _disposable.Disposable = _action(_parent, _state);
  181. }
  182. finally
  183. {
  184. SpinWait.SpinUntil(IsTimerAssigned);
  185. Stop();
  186. }
  187. }
  188. private bool IsTimerAssigned()
  189. {
  190. return _timer != null;
  191. }
  192. public void Dispose()
  193. {
  194. _disposable.Dispose();
  195. }
  196. private void Stop()
  197. {
  198. var timer = _timer;
  199. if (timer != TimerStubs.Never)
  200. {
  201. _action = Nop;
  202. _timer = TimerStubs.Never;
  203. timer.Dispose();
  204. }
  205. }
  206. private IDisposable Nop(IScheduler scheduler, TState state)
  207. {
  208. return Disposable.Empty;
  209. }
  210. }
  211. sealed class PeriodicTimer<TState> : IDisposable
  212. {
  213. private TState _state;
  214. private Func<TState, TState> _action;
  215. private readonly AsyncLock _gate;
  216. private volatile System.Threading.Timer _timer;
  217. public PeriodicTimer(TState state, TimeSpan period, Func<TState, TState> action)
  218. {
  219. _state = state;
  220. _action = action;
  221. _gate = new AsyncLock();
  222. //
  223. // Rooting of the timer happens through the this.Tick delegate's target object,
  224. // which is the current instance and has a field to store the Timer instance.
  225. //
  226. _timer = new System.Threading.Timer(this.Tick, null, period, period);
  227. }
  228. private void Tick(object state)
  229. {
  230. _gate.Wait(() =>
  231. {
  232. _state = _action(_state);
  233. });
  234. }
  235. public void Dispose()
  236. {
  237. var timer = _timer;
  238. if (timer != null)
  239. {
  240. _action = Stubs<TState>.I;
  241. _timer = null;
  242. timer.Dispose();
  243. _gate.Dispose();
  244. }
  245. }
  246. }
  247. #else
  248. abstract class Timer
  249. {
  250. //
  251. // Note: the dictionary exists to "root" the timers so that they are not garbage collected and finalized while they are running.
  252. //
  253. #if !NO_HASHSET
  254. protected static readonly HashSet<System.Threading.Timer> s_timers = new HashSet<System.Threading.Timer>();
  255. #else
  256. protected static readonly Dictionary<System.Threading.Timer, object> s_timers = new Dictionary<System.Threading.Timer, object>();
  257. #endif
  258. }
  259. sealed class Timer<TState> : Timer, IDisposable
  260. {
  261. private readonly MultipleAssignmentDisposable _disposable;
  262. private readonly IScheduler _parent;
  263. private readonly TState _state;
  264. private Func<IScheduler, TState, IDisposable> _action;
  265. private System.Threading.Timer _timer;
  266. private bool _hasAdded;
  267. private bool _hasRemoved;
  268. public Timer(IScheduler parent, TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  269. {
  270. _disposable = new MultipleAssignmentDisposable();
  271. _disposable.Disposable = Disposable.Create(Unroot);
  272. _parent = parent;
  273. _state = state;
  274. _action = action;
  275. _timer = new System.Threading.Timer(Tick, null, dueTime, TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite));
  276. lock (s_timers)
  277. {
  278. if (!_hasRemoved)
  279. {
  280. #if !NO_HASHSET
  281. s_timers.Add(_timer);
  282. #else
  283. s_timers.Add(_timer, null);
  284. #endif
  285. _hasAdded = true;
  286. }
  287. }
  288. }
  289. private void Tick(object state)
  290. {
  291. try
  292. {
  293. _disposable.Disposable = _action(_parent, _state);
  294. }
  295. finally
  296. {
  297. Unroot();
  298. }
  299. }
  300. private void Unroot()
  301. {
  302. _action = Nop;
  303. var timer = default(System.Threading.Timer);
  304. lock (s_timers)
  305. {
  306. if (!_hasRemoved)
  307. {
  308. timer = _timer;
  309. _timer = null;
  310. if (_hasAdded && timer != null)
  311. s_timers.Remove(timer);
  312. _hasRemoved = true;
  313. }
  314. }
  315. if (timer != null)
  316. timer.Dispose();
  317. }
  318. private IDisposable Nop(IScheduler scheduler, TState state)
  319. {
  320. return Disposable.Empty;
  321. }
  322. public void Dispose()
  323. {
  324. _disposable.Dispose();
  325. }
  326. }
  327. abstract class PeriodicTimer
  328. {
  329. //
  330. // Note: the dictionary exists to "root" the timers so that they are not garbage collected and finalized while they are running.
  331. //
  332. #if !NO_HASHSET
  333. protected static readonly HashSet<System.Threading.Timer> s_timers = new HashSet<System.Threading.Timer>();
  334. #else
  335. protected static readonly Dictionary<System.Threading.Timer, object> s_timers = new Dictionary<System.Threading.Timer, object>();
  336. #endif
  337. }
  338. sealed class PeriodicTimer<TState> : PeriodicTimer, IDisposable
  339. {
  340. private readonly AsyncLock _gate;
  341. private TState _state;
  342. private Func<TState, TState> _action;
  343. private System.Threading.Timer _timer;
  344. public PeriodicTimer(TState state, TimeSpan period, Func<TState, TState> action)
  345. {
  346. _gate = new AsyncLock();
  347. _state = state;
  348. _action = action;
  349. _timer = new System.Threading.Timer(Tick, null, period, period);
  350. lock (s_timers)
  351. {
  352. #if !NO_HASHSET
  353. s_timers.Add(_timer);
  354. #else
  355. s_timers.Add(_timer, null);
  356. #endif
  357. }
  358. }
  359. private void Tick(object state)
  360. {
  361. _gate.Wait(() =>
  362. {
  363. _state = _action(_state);
  364. });
  365. }
  366. public void Dispose()
  367. {
  368. var timer = default(System.Threading.Timer);
  369. lock (s_timers)
  370. {
  371. timer = _timer;
  372. _timer = null;
  373. if (timer != null)
  374. s_timers.Remove(timer);
  375. }
  376. if (timer != null)
  377. {
  378. timer.Dispose();
  379. _gate.Dispose();
  380. _action = Stubs<TState>.I;
  381. }
  382. }
  383. }
  384. #endif
  385. }
  386. }
  387. #endif