SystemClock.cs 11 KB

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