CurrentThreadScheduler.cs 6.5 KB

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