ThreadPoolScheduler.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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 ThreadPoolScheduler s_instance = new ThreadPoolScheduler();
  15. private static readonly NewThreadScheduler s_newBackgroundThread = 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;
  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.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 or equal to zero.</exception>
  106. public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action)
  107. {
  108. //
  109. // MSDN documentation states the following:
  110. //
  111. // "If period is zero (0) or negative one (-1) milliseconds and dueTime is positive, callback is invoked once;
  112. // the periodic behavior of the timer is disabled, but can be re-enabled using the Change method."
  113. //
  114. if (period <= TimeSpan.Zero)
  115. throw new ArgumentOutOfRangeException("period");
  116. if (action == null)
  117. throw new ArgumentNullException("action");
  118. return new PeriodicTimer<TState>(state, period, action);
  119. }
  120. #if USE_TIMER_SELF_ROOT
  121. //
  122. // See ConcurrencyAbstractionLayerImpl.cs for more information about the code
  123. // below and its timer rooting behavior.
  124. //
  125. sealed class Timer<TState> : IDisposable
  126. {
  127. private readonly MultipleAssignmentDisposable _disposable;
  128. private readonly IScheduler _parent;
  129. private readonly TState _state;
  130. private Func<IScheduler, TState, IDisposable> _action;
  131. private volatile System.Threading.Timer _timer;
  132. public Timer(IScheduler parent, TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  133. {
  134. _parent = parent;
  135. _state = state;
  136. _action = action;
  137. _disposable = new MultipleAssignmentDisposable();
  138. _disposable.Disposable = Disposable.Create(Stop);
  139. // Don't want the spin wait in Tick to get stuck if this thread gets aborted.
  140. try { }
  141. finally
  142. {
  143. //
  144. // Rooting of the timer happens through the this.Tick delegate's target object,
  145. // which is the current instance and has a field to store the Timer instance.
  146. //
  147. _timer = new System.Threading.Timer(this.Tick, null, dueTime, TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite));
  148. }
  149. }
  150. private void Tick(object state)
  151. {
  152. try
  153. {
  154. _disposable.Disposable = _action(_parent, _state);
  155. }
  156. finally
  157. {
  158. SpinWait.SpinUntil(IsTimerAssigned);
  159. Stop();
  160. }
  161. }
  162. private bool IsTimerAssigned()
  163. {
  164. return _timer != null;
  165. }
  166. public void Dispose()
  167. {
  168. _disposable.Dispose();
  169. }
  170. private void Stop()
  171. {
  172. var timer = _timer;
  173. if (timer != TimerStubs.Never)
  174. {
  175. _action = Nop;
  176. _timer = TimerStubs.Never;
  177. timer.Dispose();
  178. }
  179. }
  180. private IDisposable Nop(IScheduler scheduler, TState state)
  181. {
  182. return Disposable.Empty;
  183. }
  184. }
  185. sealed class PeriodicTimer<TState> : IDisposable
  186. {
  187. private TState _state;
  188. private Func<TState, TState> _action;
  189. private readonly AsyncLock _gate;
  190. private volatile System.Threading.Timer _timer;
  191. public PeriodicTimer(TState state, TimeSpan period, Func<TState, TState> action)
  192. {
  193. _state = state;
  194. _action = action;
  195. _gate = new AsyncLock();
  196. //
  197. // Rooting of the timer happens through the this.Tick delegate's target object,
  198. // which is the current instance and has a field to store the Timer instance.
  199. //
  200. _timer = new System.Threading.Timer(this.Tick, null, period, period);
  201. }
  202. private void Tick(object state)
  203. {
  204. _gate.Wait(() =>
  205. {
  206. _state = _action(_state);
  207. });
  208. }
  209. public void Dispose()
  210. {
  211. var timer = _timer;
  212. if (timer != null)
  213. {
  214. _action = Stubs<TState>.I;
  215. _timer = null;
  216. timer.Dispose();
  217. _gate.Dispose();
  218. }
  219. }
  220. }
  221. #else
  222. abstract class Timer
  223. {
  224. //
  225. // Note: the dictionary exists to "root" the timers so that they are not garbage collected and finalized while they are running.
  226. //
  227. #if !NO_HASHSET
  228. protected static readonly HashSet<System.Threading.Timer> s_timers = new HashSet<System.Threading.Timer>();
  229. #else
  230. protected static readonly Dictionary<System.Threading.Timer, object> s_timers = new Dictionary<System.Threading.Timer, object>();
  231. #endif
  232. }
  233. sealed class Timer<TState> : Timer, IDisposable
  234. {
  235. private readonly MultipleAssignmentDisposable _disposable;
  236. private readonly IScheduler _parent;
  237. private readonly TState _state;
  238. private Func<IScheduler, TState, IDisposable> _action;
  239. private System.Threading.Timer _timer;
  240. private bool _hasAdded;
  241. private bool _hasRemoved;
  242. public Timer(IScheduler parent, TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  243. {
  244. _disposable = new MultipleAssignmentDisposable();
  245. _disposable.Disposable = Disposable.Create(Unroot);
  246. _parent = parent;
  247. _state = state;
  248. _action = action;
  249. _timer = new System.Threading.Timer(Tick, null, dueTime, TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite));
  250. lock (s_timers)
  251. {
  252. if (!_hasRemoved)
  253. {
  254. #if !NO_HASHSET
  255. s_timers.Add(_timer);
  256. #else
  257. s_timers.Add(_timer, null);
  258. #endif
  259. _hasAdded = true;
  260. }
  261. }
  262. }
  263. private void Tick(object state)
  264. {
  265. try
  266. {
  267. _disposable.Disposable = _action(_parent, _state);
  268. }
  269. finally
  270. {
  271. Unroot();
  272. }
  273. }
  274. private void Unroot()
  275. {
  276. _action = Nop;
  277. var timer = default(System.Threading.Timer);
  278. lock (s_timers)
  279. {
  280. if (!_hasRemoved)
  281. {
  282. timer = _timer;
  283. _timer = null;
  284. if (_hasAdded && timer != null)
  285. s_timers.Remove(timer);
  286. _hasRemoved = true;
  287. }
  288. }
  289. if (timer != null)
  290. timer.Dispose();
  291. }
  292. private IDisposable Nop(IScheduler scheduler, TState state)
  293. {
  294. return Disposable.Empty;
  295. }
  296. public void Dispose()
  297. {
  298. _disposable.Dispose();
  299. }
  300. }
  301. abstract class PeriodicTimer
  302. {
  303. //
  304. // Note: the dictionary exists to "root" the timers so that they are not garbage collected and finalized while they are running.
  305. //
  306. #if !NO_HASHSET
  307. protected static readonly HashSet<System.Threading.Timer> s_timers = new HashSet<System.Threading.Timer>();
  308. #else
  309. protected static readonly Dictionary<System.Threading.Timer, object> s_timers = new Dictionary<System.Threading.Timer, object>();
  310. #endif
  311. }
  312. sealed class PeriodicTimer<TState> : PeriodicTimer, IDisposable
  313. {
  314. private readonly AsyncLock _gate;
  315. private TState _state;
  316. private Func<TState, TState> _action;
  317. private System.Threading.Timer _timer;
  318. public PeriodicTimer(TState state, TimeSpan period, Func<TState, TState> action)
  319. {
  320. _gate = new AsyncLock();
  321. _state = state;
  322. _action = action;
  323. _timer = new System.Threading.Timer(Tick, null, period, period);
  324. lock (s_timers)
  325. {
  326. #if !NO_HASHSET
  327. s_timers.Add(_timer);
  328. #else
  329. s_timers.Add(_timer, null);
  330. #endif
  331. }
  332. }
  333. private void Tick(object state)
  334. {
  335. _gate.Wait(() =>
  336. {
  337. _state = _action(_state);
  338. });
  339. }
  340. public void Dispose()
  341. {
  342. var timer = default(System.Threading.Timer);
  343. lock (s_timers)
  344. {
  345. timer = _timer;
  346. _timer = null;
  347. if (timer != null)
  348. s_timers.Remove(timer);
  349. }
  350. if (timer != null)
  351. {
  352. timer.Dispose();
  353. _gate.Dispose();
  354. _action = Stubs<TState>.I;
  355. }
  356. }
  357. }
  358. #endif
  359. }
  360. }
  361. #endif