DefaultScheduler.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. using System.Collections.Generic;
  3. using System.Reactive.Disposables;
  4. using System.Threading;
  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
  19. {
  20. get
  21. {
  22. return s_instance.Value;
  23. }
  24. }
  25. private DefaultScheduler()
  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. var cancel = s_cal.QueueUserWorkItem(_ =>
  42. {
  43. if (!d.IsDisposed)
  44. d.Disposable = action(this, state);
  45. }, null);
  46. return StableCompositeDisposable.Create(
  47. d,
  48. cancel
  49. );
  50. }
  51. /// <summary>
  52. /// Schedules an action to be executed after dueTime, using a System.Threading.Timer object.
  53. /// </summary>
  54. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  55. /// <param name="state">State passed to the action to be executed.</param>
  56. /// <param name="action">Action to be executed.</param>
  57. /// <param name="dueTime">Relative time after which to execute the action.</param>
  58. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  59. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  60. public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  61. {
  62. if (action == null)
  63. throw new ArgumentNullException("action");
  64. var dt = Scheduler.Normalize(dueTime);
  65. if (dt.Ticks == 0)
  66. return Schedule(state, action);
  67. var d = new SingleAssignmentDisposable();
  68. var cancel = s_cal.StartTimer(_ =>
  69. {
  70. if (!d.IsDisposed)
  71. d.Disposable = action(this, state);
  72. }, null, dt);
  73. return StableCompositeDisposable.Create(
  74. d,
  75. cancel
  76. );
  77. }
  78. /// <summary>
  79. /// Schedules a periodic piece of work, using a System.Threading.Timer object.
  80. /// </summary>
  81. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  82. /// <param name="state">Initial state passed to the action upon the first iteration.</param>
  83. /// <param name="period">Period for running the work periodically.</param>
  84. /// <param name="action">Action to be executed, potentially updating the state.</param>
  85. /// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns>
  86. /// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than TimeSpan.Zero.</exception>
  87. /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
  88. public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action)
  89. {
  90. if (period < TimeSpan.Zero)
  91. throw new ArgumentOutOfRangeException("period");
  92. if (action == null)
  93. throw new ArgumentNullException("action");
  94. var state1 = state;
  95. var gate = new AsyncLock();
  96. var cancel = s_cal.StartPeriodicTimer(() =>
  97. {
  98. gate.Wait(() =>
  99. {
  100. state1 = action(state1);
  101. });
  102. }, period);
  103. return Disposable.Create(() =>
  104. {
  105. cancel.Dispose();
  106. gate.Dispose();
  107. action = Stubs<TState>.I;
  108. });
  109. }
  110. /// <summary>
  111. /// Discovers scheduler services by interface type.
  112. /// </summary>
  113. /// <param name="serviceType">Scheduler service interface type to discover.</param>
  114. /// <returns>Object implementing the requested service, if available; null otherwise.</returns>
  115. protected override object GetService(Type serviceType)
  116. {
  117. if (serviceType == typeof(ISchedulerLongRunning))
  118. {
  119. if (s_cal.SupportsLongRunning)
  120. {
  121. return LongRunning.Instance;
  122. }
  123. }
  124. return base.GetService(serviceType);
  125. }
  126. class LongRunning : ISchedulerLongRunning
  127. {
  128. public static ISchedulerLongRunning Instance = new LongRunning();
  129. public IDisposable ScheduleLongRunning<TState>(TState state, Action<TState, ICancelable> action)
  130. {
  131. if (action == null)
  132. throw new ArgumentNullException("action");
  133. var cancel = new BooleanDisposable();
  134. DefaultScheduler.s_cal.StartThread(
  135. arg =>
  136. {
  137. var d = (ICancelable)arg;
  138. //
  139. // Notice we don't check d.IsDisposed. The contract for ISchedulerLongRunning
  140. // requires us to ensure the scheduled work gets an opportunity to observe
  141. // the cancellation request.
  142. //
  143. action(state, d);
  144. },
  145. cancel
  146. );
  147. return cancel;
  148. }
  149. }
  150. }
  151. }