DefaultScheduler.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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. using System.Reactive.Disposables;
  5. namespace System.Reactive.Concurrency
  6. {
  7. /// <summary>
  8. /// Represents an object that schedules units of work on the platform's default scheduler.
  9. /// </summary>
  10. /// <seealso cref="Scheduler.Default">Singleton instance of this type exposed through this static property.</seealso>
  11. public sealed class DefaultScheduler : LocalScheduler, ISchedulerPeriodic
  12. {
  13. private static readonly Lazy<DefaultScheduler> s_instance = new Lazy<DefaultScheduler>(() => new DefaultScheduler());
  14. private static IConcurrencyAbstractionLayer s_cal = ConcurrencyAbstractionLayer.Current;
  15. /// <summary>
  16. /// Gets the singleton instance of the default scheduler.
  17. /// </summary>
  18. public static DefaultScheduler Instance => s_instance.Value;
  19. private DefaultScheduler()
  20. {
  21. }
  22. /// <summary>
  23. /// Schedules an action to be executed.
  24. /// </summary>
  25. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  26. /// <param name="state">State passed to the action to be executed.</param>
  27. /// <param name="action">Action to be executed.</param>
  28. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  29. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  30. public override IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
  31. {
  32. if (action == null)
  33. throw new ArgumentNullException(nameof(action));
  34. var d = new SingleAssignmentDisposable();
  35. var cancel = s_cal.QueueUserWorkItem(_ =>
  36. {
  37. if (!d.IsDisposed)
  38. {
  39. d.Disposable = action(this, state);
  40. }
  41. }, null);
  42. return StableCompositeDisposable.Create(
  43. d,
  44. cancel
  45. );
  46. }
  47. /// <summary>
  48. /// Schedules an action to be executed after dueTime, using a System.Threading.Timer object.
  49. /// </summary>
  50. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  51. /// <param name="state">State passed to the action to be executed.</param>
  52. /// <param name="action">Action to be executed.</param>
  53. /// <param name="dueTime">Relative time after which to execute the action.</param>
  54. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  55. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  56. public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  57. {
  58. if (action == null)
  59. throw new ArgumentNullException(nameof(action));
  60. var dt = Scheduler.Normalize(dueTime);
  61. if (dt.Ticks == 0)
  62. return Schedule(state, action);
  63. var d = new SingleAssignmentDisposable();
  64. var cancel = s_cal.StartTimer(_ =>
  65. {
  66. if (!d.IsDisposed)
  67. {
  68. d.Disposable = action(this, state);
  69. }
  70. }, null, dt);
  71. return StableCompositeDisposable.Create(
  72. d,
  73. cancel
  74. );
  75. }
  76. /// <summary>
  77. /// Schedules a periodic piece of work, using a System.Threading.Timer object.
  78. /// </summary>
  79. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  80. /// <param name="state">Initial state passed to the action upon the first iteration.</param>
  81. /// <param name="period">Period for running the work periodically.</param>
  82. /// <param name="action">Action to be executed, potentially updating the state.</param>
  83. /// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns>
  84. /// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than <see cref="TimeSpan.Zero"/>.</exception>
  85. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  86. public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action)
  87. {
  88. if (period < TimeSpan.Zero)
  89. throw new ArgumentOutOfRangeException(nameof(period));
  90. if (action == null)
  91. throw new ArgumentNullException(nameof(action));
  92. var state1 = state;
  93. var gate = new AsyncLock();
  94. var cancel = s_cal.StartPeriodicTimer(() =>
  95. {
  96. gate.Wait(() =>
  97. {
  98. state1 = action(state1);
  99. });
  100. }, period);
  101. return Disposable.Create(() =>
  102. {
  103. cancel.Dispose();
  104. gate.Dispose();
  105. action = Stubs<TState>.I;
  106. });
  107. }
  108. /// <summary>
  109. /// Discovers scheduler services by interface type.
  110. /// </summary>
  111. /// <param name="serviceType">Scheduler service interface type to discover.</param>
  112. /// <returns>Object implementing the requested service, if available; null otherwise.</returns>
  113. protected override object GetService(Type serviceType)
  114. {
  115. if (serviceType == typeof(ISchedulerLongRunning))
  116. {
  117. if (s_cal.SupportsLongRunning)
  118. {
  119. return LongRunning.Instance;
  120. }
  121. }
  122. return base.GetService(serviceType);
  123. }
  124. private sealed class LongRunning : ISchedulerLongRunning
  125. {
  126. public static ISchedulerLongRunning Instance = new LongRunning();
  127. public IDisposable ScheduleLongRunning<TState>(TState state, Action<TState, ICancelable> action)
  128. {
  129. if (action == null)
  130. throw new ArgumentNullException(nameof(action));
  131. var cancel = new BooleanDisposable();
  132. DefaultScheduler.s_cal.StartThread(
  133. arg =>
  134. {
  135. var d = (ICancelable)arg;
  136. //
  137. // Notice we don't check d.IsDisposed. The contract for ISchedulerLongRunning
  138. // requires us to ensure the scheduled work gets an opportunity to observe
  139. // the cancellation request.
  140. //
  141. action(state, d);
  142. },
  143. cancel
  144. );
  145. return cancel;
  146. }
  147. }
  148. }
  149. }