DefaultScheduler.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. #nullable disable
  5. using System.Reactive.Disposables;
  6. namespace System.Reactive.Concurrency
  7. {
  8. /// <summary>
  9. /// Represents an object that schedules units of work on the platform's default scheduler.
  10. /// </summary>
  11. /// <seealso cref="Scheduler.Default">Singleton instance of this type exposed through this static property.</seealso>
  12. public sealed class DefaultScheduler : LocalScheduler, ISchedulerPeriodic
  13. {
  14. private static readonly Lazy<DefaultScheduler> _instance = new Lazy<DefaultScheduler>(() => new DefaultScheduler());
  15. private static readonly IConcurrencyAbstractionLayer Cal = ConcurrencyAbstractionLayer.Current;
  16. /// <summary>
  17. /// Gets the singleton instance of the default scheduler.
  18. /// </summary>
  19. public static DefaultScheduler Instance => _instance.Value;
  20. private DefaultScheduler()
  21. {
  22. }
  23. /// <summary>
  24. /// Schedules an action to be executed.
  25. /// </summary>
  26. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  27. /// <param name="state">State passed to the action to be executed.</param>
  28. /// <param name="action">Action to be executed.</param>
  29. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  30. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  31. public override IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
  32. {
  33. if (action == null)
  34. {
  35. throw new ArgumentNullException(nameof(action));
  36. }
  37. var workItem = new UserWorkItem<TState>(this, state, action);
  38. workItem.CancelQueueDisposable = Cal.QueueUserWorkItem(
  39. static closureWorkItem => ((UserWorkItem<TState>)closureWorkItem).Run(),
  40. workItem);
  41. return workItem;
  42. }
  43. /// <summary>
  44. /// Schedules an action to be executed after dueTime, using a System.Threading.Timer object.
  45. /// </summary>
  46. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  47. /// <param name="state">State passed to the action to be executed.</param>
  48. /// <param name="action">Action to be executed.</param>
  49. /// <param name="dueTime">Relative time after which to execute the action.</param>
  50. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  51. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  52. public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  53. {
  54. if (action == null)
  55. {
  56. throw new ArgumentNullException(nameof(action));
  57. }
  58. var dt = Scheduler.Normalize(dueTime);
  59. if (dt.Ticks == 0)
  60. {
  61. return Schedule(state, action);
  62. }
  63. var workItem = new UserWorkItem<TState>(this, state, action);
  64. workItem.CancelQueueDisposable = Cal.StartTimer(
  65. static closureWorkItem => ((UserWorkItem<TState>)closureWorkItem).Run(),
  66. workItem,
  67. dt);
  68. return workItem;
  69. }
  70. /// <summary>
  71. /// Schedules a periodic piece of work, using a System.Threading.Timer object.
  72. /// </summary>
  73. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  74. /// <param name="state">Initial state passed to the action upon the first iteration.</param>
  75. /// <param name="period">Period for running the work periodically.</param>
  76. /// <param name="action">Action to be executed, potentially updating the state.</param>
  77. /// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns>
  78. /// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than <see cref="TimeSpan.Zero"/>.</exception>
  79. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  80. public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action)
  81. {
  82. if (period < TimeSpan.Zero)
  83. {
  84. throw new ArgumentOutOfRangeException(nameof(period));
  85. }
  86. if (action == null)
  87. {
  88. throw new ArgumentNullException(nameof(action));
  89. }
  90. return new PeriodicallyScheduledWorkItem<TState>(state, period, action);
  91. }
  92. private sealed class PeriodicallyScheduledWorkItem<TState> : IDisposable
  93. {
  94. private TState _state;
  95. private Func<TState, TState> _action;
  96. private readonly IDisposable _cancel;
  97. private readonly AsyncLock _gate = new AsyncLock();
  98. public PeriodicallyScheduledWorkItem(TState state, TimeSpan period, Func<TState, TState> action)
  99. {
  100. _state = state;
  101. _action = action;
  102. _cancel = Cal.StartPeriodicTimer(Tick, period);
  103. }
  104. private void Tick()
  105. {
  106. _gate.Wait(
  107. this,
  108. static closureWorkItem => closureWorkItem._state = closureWorkItem._action(closureWorkItem._state));
  109. }
  110. public void Dispose()
  111. {
  112. _cancel.Dispose();
  113. _gate.Dispose();
  114. _action = Stubs<TState>.I;
  115. }
  116. }
  117. /// <summary>
  118. /// Discovers scheduler services by interface type.
  119. /// </summary>
  120. /// <param name="serviceType">Scheduler service interface type to discover.</param>
  121. /// <returns>Object implementing the requested service, if available; null otherwise.</returns>
  122. protected override object GetService(Type serviceType)
  123. {
  124. if (serviceType == typeof(ISchedulerLongRunning))
  125. {
  126. if (Cal.SupportsLongRunning)
  127. {
  128. return LongRunning.Instance;
  129. }
  130. }
  131. return base.GetService(serviceType);
  132. }
  133. private sealed class LongRunning : ISchedulerLongRunning
  134. {
  135. private sealed class LongScheduledWorkItem<TState> : ICancelable
  136. {
  137. private readonly TState _state;
  138. private readonly Action<TState, ICancelable> _action;
  139. private IDisposable _cancel;
  140. public LongScheduledWorkItem(TState state, Action<TState, ICancelable> action)
  141. {
  142. _state = state;
  143. _action = action;
  144. Cal.StartThread(
  145. thisObject =>
  146. {
  147. var @this = (LongScheduledWorkItem<TState>)thisObject;
  148. //
  149. // Notice we don't check d.IsDisposed. The contract for ISchedulerLongRunning
  150. // requires us to ensure the scheduled work gets an opportunity to observe
  151. // the cancellation request.
  152. //
  153. @this._action(@this._state, @this);
  154. },
  155. this
  156. );
  157. }
  158. public void Dispose()
  159. {
  160. Disposable.TryDispose(ref _cancel);
  161. }
  162. public bool IsDisposed => Disposable.GetIsDisposed(ref _cancel);
  163. }
  164. public static readonly ISchedulerLongRunning Instance = new LongRunning();
  165. public IDisposable ScheduleLongRunning<TState>(TState state, Action<TState, ICancelable> action)
  166. {
  167. if (action == null)
  168. {
  169. throw new ArgumentNullException(nameof(action));
  170. }
  171. return new LongScheduledWorkItem<TState>(state, action);
  172. }
  173. }
  174. }
  175. }