ThreadPoolScheduler.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. /// <summary>
  16. /// Gets the singleton instance of the CLR thread pool scheduler.
  17. /// </summary>
  18. public static ThreadPoolScheduler Instance
  19. {
  20. get
  21. {
  22. return s_instance;
  23. }
  24. }
  25. ThreadPoolScheduler()
  26. {
  27. }
  28. /// <summary>
  29. /// Schedules an action to be executed.
  30. /// </summary>
  31. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  32. /// <param name="state">State passed to the action to be executed.</param>
  33. /// <param name="action">Action to be executed.</param>
  34. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  35. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  36. public override IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
  37. {
  38. if (action == null)
  39. throw new ArgumentNullException("action");
  40. var d = new SingleAssignmentDisposable();
  41. ThreadPool.QueueUserWorkItem(_ =>
  42. {
  43. if (!d.IsDisposed)
  44. d.Disposable = action(this, state);
  45. }, null);
  46. return d;
  47. }
  48. /// <summary>
  49. /// Schedules an action to be executed after dueTime, using a System.Threading.Timer object.
  50. /// </summary>
  51. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  52. /// <param name="state">State passed to the action to be executed.</param>
  53. /// <param name="action">Action to be executed.</param>
  54. /// <param name="dueTime">Relative time after which to execute the action.</param>
  55. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  56. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  57. public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  58. {
  59. if (action == null)
  60. throw new ArgumentNullException("action");
  61. var dt = Scheduler.Normalize(dueTime);
  62. if (dt.Ticks == 0)
  63. return Schedule(state, action);
  64. return new Timer<TState>(this, state, dt, action);
  65. }
  66. /// <summary>
  67. /// Schedules a long-running task by creating a new thread. Cancellation happens through polling.
  68. /// </summary>
  69. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  70. /// <param name="state">State passed to the action to be executed.</param>
  71. /// <param name="action">Action to be executed.</param>
  72. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  73. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  74. public IDisposable ScheduleLongRunning<TState>(TState state, Action<TState, ICancelable> action)
  75. {
  76. if (action == null)
  77. throw new ArgumentNullException("action");
  78. return NewThreadScheduler.Default.ScheduleLongRunning(state, action);
  79. }
  80. #if !NO_STOPWATCH
  81. /// <summary>
  82. /// Starts a new stopwatch object.
  83. /// </summary>
  84. /// <returns>New stopwatch object; started at the time of the request.</returns>
  85. public override IStopwatch StartStopwatch()
  86. {
  87. //
  88. // Strictly speaking, this explicit override is not necessary because the base implementation calls into
  89. // the enlightenment module to obtain the CAL, which would circle back to System.Reactive.PlatformServices
  90. // where we're currently running. This is merely a short-circuit to avoid the additional roundtrip.
  91. //
  92. return new StopwatchImpl();
  93. }
  94. #endif
  95. /// <summary>
  96. /// Schedules a periodic piece of work, using a System.Threading.Timer object.
  97. /// </summary>
  98. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  99. /// <param name="state">Initial state passed to the action upon the first iteration.</param>
  100. /// <param name="period">Period for running the work periodically.</param>
  101. /// <param name="action">Action to be executed, potentially updating the state.</param>
  102. /// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns>
  103. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  104. /// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than or equal to zero.</exception>
  105. public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action)
  106. {
  107. //
  108. // MSDN documentation states the following:
  109. //
  110. // "If period is zero (0) or negative one (-1) milliseconds and dueTime is positive, callback is invoked once;
  111. // the periodic behavior of the timer is disabled, but can be re-enabled using the Change method."
  112. //
  113. if (period <= TimeSpan.Zero)
  114. throw new ArgumentOutOfRangeException("period");
  115. if (action == null)
  116. throw new ArgumentNullException("action");
  117. return new PeriodicTimer<TState>(state, period, action);
  118. }
  119. #if USE_TIMER_SELF_ROOT
  120. //
  121. // See ConcurrencyAbstractionLayerImpl.cs for more information about the code
  122. // below and its timer rooting behavior.
  123. //
  124. sealed class Timer<TState> : IDisposable
  125. {
  126. private readonly MultipleAssignmentDisposable _disposable;
  127. private readonly IScheduler _parent;
  128. private readonly TState _state;
  129. private Func<IScheduler, TState, IDisposable> _action;
  130. private volatile System.Threading.Timer _timer;
  131. public Timer(IScheduler parent, TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  132. {
  133. _parent = parent;
  134. _state = state;
  135. _action = action;
  136. _disposable = new MultipleAssignmentDisposable();
  137. _disposable.Disposable = Disposable.Create(Stop);
  138. // Don't want the spin wait in Tick to get stuck if this thread gets aborted.
  139. try { }
  140. finally
  141. {
  142. //
  143. // Rooting of the timer happens through the this.Tick delegate's target object,
  144. // which is the current instance and has a field to store the Timer instance.
  145. //
  146. _timer = new System.Threading.Timer(this.Tick, null, dueTime, TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite));
  147. }
  148. }
  149. private void Tick(object state)
  150. {
  151. try
  152. {
  153. _disposable.Disposable = _action(_parent, _state);
  154. }
  155. finally
  156. {
  157. SpinWait.SpinUntil(IsTimerAssigned);
  158. Stop();
  159. }
  160. }
  161. private bool IsTimerAssigned()
  162. {
  163. return _timer != null;
  164. }
  165. public void Dispose()
  166. {
  167. _disposable.Dispose();
  168. }
  169. private void Stop()
  170. {
  171. var timer = _timer;
  172. if (timer != TimerStubs.Never)
  173. {
  174. _action = Nop;
  175. _timer = TimerStubs.Never;
  176. timer.Dispose();
  177. }
  178. }
  179. private IDisposable Nop(IScheduler scheduler, TState state)
  180. {
  181. return Disposable.Empty;
  182. }
  183. }
  184. sealed class PeriodicTimer<TState> : IDisposable
  185. {
  186. private TState _state;
  187. private Func<TState, TState> _action;
  188. private readonly AsyncLock _gate;
  189. private volatile System.Threading.Timer _timer;
  190. public PeriodicTimer(TState state, TimeSpan period, Func<TState, TState> action)
  191. {
  192. _state = state;
  193. _action = action;
  194. _gate = new AsyncLock();
  195. //
  196. // Rooting of the timer happens through the this.Tick delegate's target object,
  197. // which is the current instance and has a field to store the Timer instance.
  198. //
  199. _timer = new System.Threading.Timer(this.Tick, null, period, period);
  200. }
  201. private void Tick(object state)
  202. {
  203. _gate.Wait(() =>
  204. {
  205. _state = _action(_state);
  206. });
  207. }
  208. public void Dispose()
  209. {
  210. var timer = _timer;
  211. if (timer != null)
  212. {
  213. _action = Stubs<TState>.I;
  214. _timer = null;
  215. timer.Dispose();
  216. _gate.Dispose();
  217. }
  218. }
  219. }
  220. #else
  221. abstract class Timer
  222. {
  223. //
  224. // Note: the dictionary exists to "root" the timers so that they are not garbage collected and finalized while they are running.
  225. //
  226. #if !NO_HASHSET
  227. protected static readonly HashSet<System.Threading.Timer> s_timers = new HashSet<System.Threading.Timer>();
  228. #else
  229. protected static readonly Dictionary<System.Threading.Timer, object> s_timers = new Dictionary<System.Threading.Timer, object>();
  230. #endif
  231. }
  232. sealed class Timer<TState> : Timer, IDisposable
  233. {
  234. private readonly MultipleAssignmentDisposable _disposable;
  235. private readonly IScheduler _parent;
  236. private readonly TState _state;
  237. private Func<IScheduler, TState, IDisposable> _action;
  238. private System.Threading.Timer _timer;
  239. private bool _hasAdded;
  240. private bool _hasRemoved;
  241. public Timer(IScheduler parent, TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  242. {
  243. _disposable = new MultipleAssignmentDisposable();
  244. _disposable.Disposable = Disposable.Create(Unroot);
  245. _parent = parent;
  246. _state = state;
  247. _action = action;
  248. _timer = new System.Threading.Timer(Tick, null, dueTime, TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite));
  249. lock (s_timers)
  250. {
  251. if (!_hasRemoved)
  252. {
  253. #if !NO_HASHSET
  254. s_timers.Add(_timer);
  255. #else
  256. s_timers.Add(_timer, null);
  257. #endif
  258. _hasAdded = true;
  259. }
  260. }
  261. }
  262. private void Tick(object state)
  263. {
  264. try
  265. {
  266. _disposable.Disposable = _action(_parent, _state);
  267. }
  268. finally
  269. {
  270. Unroot();
  271. }
  272. }
  273. private void Unroot()
  274. {
  275. _action = Nop;
  276. var timer = default(System.Threading.Timer);
  277. lock (s_timers)
  278. {
  279. if (!_hasRemoved)
  280. {
  281. timer = _timer;
  282. _timer = null;
  283. if (_hasAdded && timer != null)
  284. s_timers.Remove(timer);
  285. _hasRemoved = true;
  286. }
  287. }
  288. if (timer != null)
  289. timer.Dispose();
  290. }
  291. private IDisposable Nop(IScheduler scheduler, TState state)
  292. {
  293. return Disposable.Empty;
  294. }
  295. public void Dispose()
  296. {
  297. _disposable.Dispose();
  298. }
  299. }
  300. abstract class PeriodicTimer
  301. {
  302. //
  303. // Note: the dictionary exists to "root" the timers so that they are not garbage collected and finalized while they are running.
  304. //
  305. #if !NO_HASHSET
  306. protected static readonly HashSet<System.Threading.Timer> s_timers = new HashSet<System.Threading.Timer>();
  307. #else
  308. protected static readonly Dictionary<System.Threading.Timer, object> s_timers = new Dictionary<System.Threading.Timer, object>();
  309. #endif
  310. }
  311. sealed class PeriodicTimer<TState> : PeriodicTimer, IDisposable
  312. {
  313. private readonly AsyncLock _gate;
  314. private TState _state;
  315. private Func<TState, TState> _action;
  316. private System.Threading.Timer _timer;
  317. public PeriodicTimer(TState state, TimeSpan period, Func<TState, TState> action)
  318. {
  319. _gate = new AsyncLock();
  320. _state = state;
  321. _action = action;
  322. _timer = new System.Threading.Timer(Tick, null, period, period);
  323. lock (s_timers)
  324. {
  325. #if !NO_HASHSET
  326. s_timers.Add(_timer);
  327. #else
  328. s_timers.Add(_timer, null);
  329. #endif
  330. }
  331. }
  332. private void Tick(object state)
  333. {
  334. _gate.Wait(() =>
  335. {
  336. _state = _action(_state);
  337. });
  338. }
  339. public void Dispose()
  340. {
  341. var timer = default(System.Threading.Timer);
  342. lock (s_timers)
  343. {
  344. timer = _timer;
  345. _timer = null;
  346. if (timer != null)
  347. s_timers.Remove(timer);
  348. }
  349. if (timer != null)
  350. {
  351. timer.Dispose();
  352. _gate.Dispose();
  353. _action = Stubs<TState>.I;
  354. }
  355. }
  356. }
  357. #endif
  358. }
  359. }
  360. #endif