ThreadPoolScheduler.cs 9.2 KB

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