DefaultScheduler.cs 7.0 KB

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