CurrentThreadScheduler.cs 6.4 KB

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