CurrentThreadScheduler.cs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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. private CurrentThreadScheduler()
  17. {
  18. }
  19. /// <summary>
  20. /// Gets the singleton instance of the current thread scheduler.
  21. /// </summary>
  22. public static CurrentThreadScheduler Instance => s_instance.Value;
  23. [ThreadStatic]
  24. private static SchedulerQueue<TimeSpan> s_threadLocalQueue;
  25. [ThreadStatic]
  26. private static IStopwatch s_clock;
  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. s_clock = ConcurrencyAbstractionLayer.Current.StartStopwatch();
  38. return s_clock.Elapsed;
  39. }
  40. }
  41. /// <summary>
  42. /// Gets a value that indicates whether the caller must call a Schedule method.
  43. /// </summary>
  44. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Now marked as obsolete.")]
  45. [EditorBrowsable(EditorBrowsableState.Never)]
  46. [Obsolete(Constants_Core.OBSOLETE_SCHEDULEREQUIRED)] // Preferring static method call over instance method call.
  47. public bool ScheduleRequired => IsScheduleRequired;
  48. /// <summary>
  49. /// Gets a value that indicates whether the caller must call a Schedule method.
  50. /// </summary>
  51. [EditorBrowsable(EditorBrowsableState.Advanced)]
  52. public static bool IsScheduleRequired => GetQueue() == null;
  53. /// <summary>
  54. /// Schedules an action to be executed after dueTime.
  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 <c>null</c>.</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 = Time + Scheduler.Normalize(dueTime);
  67. var si = new ScheduledItem<TimeSpan, TState>(this, state, action, dt);
  68. var queue = GetQueue();
  69. if (queue == null)
  70. {
  71. queue = new SchedulerQueue<TimeSpan>(4);
  72. queue.Enqueue(si);
  73. SetQueue(queue);
  74. try
  75. {
  76. Trampoline.Run(queue);
  77. }
  78. finally
  79. {
  80. SetQueue(null);
  81. }
  82. }
  83. else
  84. {
  85. queue.Enqueue(si);
  86. }
  87. return Disposable.Create(si.Cancel);
  88. }
  89. private static class Trampoline
  90. {
  91. public static void Run(SchedulerQueue<TimeSpan> queue)
  92. {
  93. while (queue.Count > 0)
  94. {
  95. var item = queue.Dequeue();
  96. if (!item.IsCanceled)
  97. {
  98. var wait = item.DueTime - Time;
  99. if (wait.Ticks > 0)
  100. {
  101. ConcurrencyAbstractionLayer.Current.Sleep(wait);
  102. }
  103. if (!item.IsCanceled)
  104. {
  105. item.Invoke();
  106. }
  107. }
  108. }
  109. }
  110. }
  111. }
  112. }