1
0

SystemClock.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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.Collections.Generic;
  5. using System.ComponentModel;
  6. using System.Reactive.Concurrency;
  7. using System.Threading;
  8. namespace System.Reactive.PlatformServices
  9. {
  10. /// <summary>
  11. /// (Infrastructure) Provides access to local system clock services.
  12. /// </summary>
  13. /// <remarks>
  14. /// This type is used by the Rx infrastructure and not meant for public consumption or implementation.
  15. /// No guarantees are made about forward compatibility of the type's functionality and its usage.
  16. /// </remarks>
  17. [EditorBrowsable(EditorBrowsableState.Never)]
  18. public static class SystemClock
  19. {
  20. private static Lazy<ISystemClock> s_serviceSystemClock = new Lazy<ISystemClock>(InitializeSystemClock);
  21. private static Lazy<INotifySystemClockChanged> s_serviceSystemClockChanged = new Lazy<INotifySystemClockChanged>(InitializeSystemClockChanged);
  22. private static readonly HashSet<WeakReference<LocalScheduler>> s_systemClockChanged = new HashSet<WeakReference<LocalScheduler>>();
  23. private static IDisposable s_systemClockChangedHandlerCollector;
  24. private static int _refCount;
  25. /// <summary>
  26. /// Gets the local system clock time.
  27. /// </summary>
  28. public static DateTimeOffset UtcNow
  29. {
  30. get { return s_serviceSystemClock.Value.UtcNow; }
  31. }
  32. /// <summary>
  33. /// Adds a reference to the system clock monitor, causing it to be sending notifications.
  34. /// </summary>
  35. /// <exception cref="NotSupportedException">Thrown when the system doesn't support sending clock change notifications.</exception>
  36. public static void AddRef()
  37. {
  38. if (Interlocked.Increment(ref _refCount) == 1)
  39. {
  40. s_serviceSystemClockChanged.Value.SystemClockChanged += OnSystemClockChanged;
  41. }
  42. }
  43. /// <summary>
  44. /// Removes a reference to the system clock monitor, causing it to stop sending notifications
  45. /// if the removed reference was the last one.
  46. /// </summary>
  47. public static void Release()
  48. {
  49. if (Interlocked.Decrement(ref _refCount) == 0)
  50. {
  51. s_serviceSystemClockChanged.Value.SystemClockChanged -= OnSystemClockChanged;
  52. }
  53. }
  54. private static void OnSystemClockChanged(object sender, SystemClockChangedEventArgs e)
  55. {
  56. lock (s_systemClockChanged)
  57. {
  58. foreach (var entry in s_systemClockChanged)
  59. {
  60. var scheduler = default(LocalScheduler);
  61. if (entry.TryGetTarget(out scheduler))
  62. {
  63. scheduler.SystemClockChanged(sender, e);
  64. }
  65. }
  66. }
  67. }
  68. private static ISystemClock InitializeSystemClock()
  69. {
  70. #pragma warning disable CS0618 // Type or member is obsolete
  71. return PlatformEnlightenmentProvider.Current.GetService<ISystemClock>() ?? new DefaultSystemClock();
  72. #pragma warning restore CS0618 // Type or member is obsolete
  73. }
  74. private static INotifySystemClockChanged InitializeSystemClockChanged()
  75. {
  76. #pragma warning disable CS0618 // Type or member is obsolete
  77. return PlatformEnlightenmentProvider.Current.GetService<INotifySystemClockChanged>() ?? new DefaultSystemClockMonitor();
  78. #pragma warning restore CS0618 // Type or member is obsolete
  79. }
  80. internal static void Register(LocalScheduler scheduler)
  81. {
  82. //
  83. // LocalScheduler maintains per-instance work queues that need revisiting
  84. // upon system clock changes. We need to be careful to avoid keeping those
  85. // scheduler instances alive by the system clock monitor, so we use weak
  86. // references here. In particular, AsyncLockScheduler in ImmediateScheduler
  87. // can have a lot of instances, so we need to collect spurious handlers
  88. // at regular times.
  89. //
  90. lock (s_systemClockChanged)
  91. {
  92. s_systemClockChanged.Add(new WeakReference<LocalScheduler>(scheduler));
  93. if (s_systemClockChanged.Count == 1)
  94. {
  95. s_systemClockChangedHandlerCollector = ConcurrencyAbstractionLayer.Current.StartPeriodicTimer(CollectHandlers, TimeSpan.FromSeconds(30));
  96. }
  97. else if (s_systemClockChanged.Count % 64 == 0)
  98. {
  99. CollectHandlers();
  100. }
  101. }
  102. }
  103. private static void CollectHandlers()
  104. {
  105. //
  106. // The handler collector merely collects the WeakReference<T> instances
  107. // that are kept in the hash set. The underlying scheduler itself will
  108. // be collected due to the weak reference. Unfortunately, we can't use
  109. // the ConditionalWeakTable<TKey, TValue> type here because we need to
  110. // be able to enumerate the keys.
  111. //
  112. lock (s_systemClockChanged)
  113. {
  114. var remove = default(HashSet<WeakReference<LocalScheduler>>);
  115. foreach (var handler in s_systemClockChanged)
  116. {
  117. var scheduler = default(LocalScheduler);
  118. if (!handler.TryGetTarget(out scheduler))
  119. {
  120. if (remove == null)
  121. {
  122. remove = new HashSet<WeakReference<LocalScheduler>>();
  123. }
  124. remove.Add(handler);
  125. }
  126. }
  127. if (remove != null)
  128. {
  129. foreach (var handler in remove)
  130. {
  131. s_systemClockChanged.Remove(handler);
  132. }
  133. }
  134. if (s_systemClockChanged.Count == 0)
  135. {
  136. s_systemClockChangedHandlerCollector.Dispose();
  137. s_systemClockChangedHandlerCollector = null;
  138. }
  139. }
  140. }
  141. }
  142. /// <summary>
  143. /// (Infrastructure) Provides access to the local system clock.
  144. /// </summary>
  145. /// <remarks>
  146. /// This type is used by the Rx infrastructure and not meant for public consumption or implementation.
  147. /// No guarantees are made about forward compatibility of the type's functionality and its usage.
  148. /// </remarks>
  149. [EditorBrowsable(EditorBrowsableState.Never)]
  150. public interface ISystemClock
  151. {
  152. /// <summary>
  153. /// Gets the current time.
  154. /// </summary>
  155. DateTimeOffset UtcNow { get; }
  156. }
  157. /// <summary>
  158. /// (Infrastructure) Provides a mechanism to notify local schedulers about system clock changes.
  159. /// </summary>
  160. /// <remarks>
  161. /// This type is used by the Rx infrastructure and not meant for public consumption or implementation.
  162. /// No guarantees are made about forward compatibility of the type's functionality and its usage.
  163. /// </remarks>
  164. [EditorBrowsable(EditorBrowsableState.Never)]
  165. public interface INotifySystemClockChanged
  166. {
  167. /// <summary>
  168. /// Event that gets raised when a system clock change is detected.
  169. /// </summary>
  170. event EventHandler<SystemClockChangedEventArgs> SystemClockChanged;
  171. }
  172. /// <summary>
  173. /// (Infrastructure) Event arguments for system clock change notifications.
  174. /// </summary>
  175. /// <remarks>
  176. /// This type is used by the Rx infrastructure and not meant for public consumption or implementation.
  177. /// No guarantees are made about forward compatibility of the type's functionality and its usage.
  178. /// </remarks>
  179. [EditorBrowsable(EditorBrowsableState.Never)]
  180. public class SystemClockChangedEventArgs : EventArgs
  181. {
  182. /// <summary>
  183. /// Creates a new system clock notification object with unknown old and new times.
  184. /// </summary>
  185. public SystemClockChangedEventArgs()
  186. : this(DateTimeOffset.MinValue, DateTimeOffset.MaxValue)
  187. {
  188. }
  189. /// <summary>
  190. /// Creates a new system clock notification object with the specified old and new times.
  191. /// </summary>
  192. /// <param name="oldTime">Time before the system clock changed, or DateTimeOffset.MinValue if not known.</param>
  193. /// <param name="newTime">Time after the system clock changed, or DateTimeOffset.MaxValue if not known.</param>
  194. public SystemClockChangedEventArgs(DateTimeOffset oldTime, DateTimeOffset newTime)
  195. {
  196. OldTime = oldTime;
  197. NewTime = newTime;
  198. }
  199. /// <summary>
  200. /// Gets the time before the system clock changed, or DateTimeOffset.MinValue if not known.
  201. /// </summary>
  202. public DateTimeOffset OldTime { get; private set; }
  203. /// <summary>
  204. /// Gets the time after the system clock changed, or DateTimeOffset.MaxValue if not known.
  205. /// </summary>
  206. public DateTimeOffset NewTime { get; private set; }
  207. }
  208. }