CurrentThreadScheduler.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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.ComponentModel;
  5. namespace System.Reactive.Concurrency
  6. {
  7. /// <summary>
  8. /// Represents an object that schedules units of work on the current thread.
  9. /// </summary>
  10. /// <seealso cref="Scheduler.CurrentThread">Singleton instance of this type exposed through this static property.</seealso>
  11. public sealed class CurrentThreadScheduler : LocalScheduler
  12. {
  13. private static readonly Lazy<CurrentThreadScheduler> s_instance = new Lazy<CurrentThreadScheduler>(() => new CurrentThreadScheduler());
  14. private CurrentThreadScheduler()
  15. {
  16. }
  17. /// <summary>
  18. /// Gets the singleton instance of the current thread scheduler.
  19. /// </summary>
  20. public static CurrentThreadScheduler Instance => s_instance.Value;
  21. [ThreadStatic]
  22. private static SchedulerQueue<TimeSpan> s_threadLocalQueue;
  23. [ThreadStatic]
  24. private static IStopwatch s_clock;
  25. [ThreadStatic]
  26. private static bool running;
  27. private static SchedulerQueue<TimeSpan> GetQueue() => s_threadLocalQueue;
  28. private static void SetQueue(SchedulerQueue<TimeSpan> newQueue)
  29. {
  30. s_threadLocalQueue = newQueue;
  31. }
  32. private static TimeSpan Time
  33. {
  34. get
  35. {
  36. if (s_clock == null)
  37. {
  38. s_clock = ConcurrencyAbstractionLayer.Current.StartStopwatch();
  39. }
  40. return s_clock.Elapsed;
  41. }
  42. }
  43. /// <summary>
  44. /// Gets a value that indicates whether the caller must call a Schedule method.
  45. /// </summary>
  46. [Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Now marked as obsolete.")]
  47. [EditorBrowsable(EditorBrowsableState.Never)]
  48. [Obsolete(Constants_Core.OBSOLETE_SCHEDULEREQUIRED)] // Preferring static method call over instance method call.
  49. public bool ScheduleRequired => IsScheduleRequired;
  50. /// <summary>
  51. /// Gets a value that indicates whether the caller must call a Schedule method.
  52. /// </summary>
  53. [EditorBrowsable(EditorBrowsableState.Advanced)]
  54. public static bool IsScheduleRequired => !running;
  55. /// <summary>
  56. /// Schedules an action to be executed after dueTime.
  57. /// </summary>
  58. /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
  59. /// <param name="state">State passed to the action to be executed.</param>
  60. /// <param name="action">Action to be executed.</param>
  61. /// <param name="dueTime">Relative time after which to execute the action.</param>
  62. /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
  63. /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
  64. public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
  65. {
  66. if (action == null)
  67. {
  68. throw new ArgumentNullException(nameof(action));
  69. }
  70. var queue = default(SchedulerQueue<TimeSpan>);
  71. // There is no timed task and no task is currently running
  72. if (!running)
  73. {
  74. running = true;
  75. if (dueTime > TimeSpan.Zero)
  76. {
  77. ConcurrencyAbstractionLayer.Current.Sleep(dueTime);
  78. }
  79. // execute directly without queueing
  80. IDisposable d;
  81. try
  82. {
  83. d = action(this, state);
  84. }
  85. catch
  86. {
  87. SetQueue(null);
  88. running = false;
  89. throw;
  90. }
  91. // did recursive tasks arrive?
  92. queue = GetQueue();
  93. // yes, run those in the queue as well
  94. if (queue != null)
  95. {
  96. try
  97. {
  98. Trampoline.Run(queue);
  99. }
  100. finally
  101. {
  102. SetQueue(null);
  103. running = false;
  104. }
  105. }
  106. else
  107. {
  108. running = false;
  109. }
  110. return d;
  111. }
  112. queue = GetQueue();
  113. // if there is a task running or there is a queue
  114. if (queue == null)
  115. {
  116. queue = new SchedulerQueue<TimeSpan>(4);
  117. SetQueue(queue);
  118. }
  119. var dt = Time + Scheduler.Normalize(dueTime);
  120. // queue up more work
  121. var si = new ScheduledItem<TimeSpan, TState>(this, state, action, dt);
  122. queue.Enqueue(si);
  123. return si;
  124. }
  125. private static class Trampoline
  126. {
  127. public static void Run(SchedulerQueue<TimeSpan> queue)
  128. {
  129. while (queue.Count > 0)
  130. {
  131. var item = queue.Dequeue();
  132. if (!item.IsCanceled)
  133. {
  134. var wait = item.DueTime - Time;
  135. if (wait.Ticks > 0)
  136. {
  137. ConcurrencyAbstractionLayer.Current.Sleep(wait);
  138. }
  139. if (!item.IsCanceled)
  140. {
  141. item.Invoke();
  142. }
  143. }
  144. }
  145. }
  146. }
  147. }
  148. }