SystemClock.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. return PlatformEnlightenmentProvider.Current.GetService<ISystemClock>() ?? new DefaultSystemClock();
  81. }
  82. private static INotifySystemClockChanged InitializeSystemClockChanged()
  83. {
  84. return PlatformEnlightenmentProvider.Current.GetService<INotifySystemClockChanged>() ?? new DefaultSystemClockMonitor();
  85. }
  86. internal static void Register(LocalScheduler scheduler)
  87. {
  88. //
  89. // LocalScheduler maintains per-instance work queues that need revisiting
  90. // upon system clock changes. We need to be careful to avoid keeping those
  91. // scheduler instances alive by the system clock monitor, so we use weak
  92. // references here. In particular, AsyncLockScheduler in ImmediateScheduler
  93. // can have a lot of instances, so we need to collect spurious handlers
  94. // at regular times.
  95. //
  96. lock (s_systemClockChanged)
  97. {
  98. #if NO_WEAKREFOFT
  99. s_systemClockChanged.Add(new WeakReference(scheduler, false));
  100. #else
  101. s_systemClockChanged.Add(new WeakReference<LocalScheduler>(scheduler));
  102. #endif
  103. if (s_systemClockChanged.Count == 1)
  104. {
  105. s_systemClockChangedHandlerCollector = ConcurrencyAbstractionLayer.Current.StartPeriodicTimer(CollectHandlers, TimeSpan.FromSeconds(30));
  106. }
  107. else if (s_systemClockChanged.Count % 64 == 0)
  108. {
  109. CollectHandlers();
  110. }
  111. }
  112. }
  113. private static void CollectHandlers()
  114. {
  115. //
  116. // The handler collector merely collects the WeakReference<T> instances
  117. // that are kept in the hash set. The underlying scheduler itself will
  118. // be collected due to the weak reference. Unfortunately, we can't use
  119. // the ConditionalWeakTable<TKey, TValue> type here because we need to
  120. // be able to enumerate the keys.
  121. //
  122. lock (s_systemClockChanged)
  123. {
  124. #if NO_WEAKREFOFT
  125. var remove = default(HashSet<WeakReference>);
  126. #else
  127. var remove = default(HashSet<WeakReference<LocalScheduler>>);
  128. #endif
  129. foreach (var handler in s_systemClockChanged)
  130. {
  131. #if NO_WEAKREFOFT
  132. var scheduler = handler.Target as LocalScheduler;
  133. if (scheduler == null)
  134. #else
  135. var scheduler = default(LocalScheduler);
  136. if (!handler.TryGetTarget(out scheduler))
  137. #endif
  138. {
  139. if (remove == null)
  140. {
  141. #if NO_WEAKREFOFT
  142. remove = new HashSet<WeakReference>();
  143. #else
  144. remove = new HashSet<WeakReference<LocalScheduler>>();
  145. #endif
  146. }
  147. remove.Add(handler);
  148. }
  149. }
  150. if (remove != null)
  151. {
  152. foreach (var handler in remove)
  153. {
  154. s_systemClockChanged.Remove(handler);
  155. }
  156. }
  157. if (s_systemClockChanged.Count == 0)
  158. {
  159. s_systemClockChangedHandlerCollector.Dispose();
  160. s_systemClockChangedHandlerCollector = null;
  161. }
  162. }
  163. }
  164. }
  165. /// <summary>
  166. /// (Infrastructure) Provides access to the local system clock.
  167. /// </summary>
  168. /// <remarks>
  169. /// This type is used by the Rx infrastructure and not meant for public consumption or implementation.
  170. /// No guarantees are made about forward compatibility of the type's functionality and its usage.
  171. /// </remarks>
  172. [EditorBrowsable(EditorBrowsableState.Never)]
  173. public interface ISystemClock
  174. {
  175. /// <summary>
  176. /// Gets the current time.
  177. /// </summary>
  178. DateTimeOffset UtcNow { get; }
  179. }
  180. /// <summary>
  181. /// (Infrastructure) Provides a mechanism to notify local schedulers about system clock changes.
  182. /// </summary>
  183. /// <remarks>
  184. /// This type is used by the Rx infrastructure and not meant for public consumption or implementation.
  185. /// No guarantees are made about forward compatibility of the type's functionality and its usage.
  186. /// </remarks>
  187. [EditorBrowsable(EditorBrowsableState.Never)]
  188. public interface INotifySystemClockChanged
  189. {
  190. /// <summary>
  191. /// Event that gets raised when a system clock change is detected.
  192. /// </summary>
  193. event EventHandler<SystemClockChangedEventArgs> SystemClockChanged;
  194. }
  195. /// <summary>
  196. /// (Infrastructure) Event arguments for system clock change notifications.
  197. /// </summary>
  198. /// <remarks>
  199. /// This type is used by the Rx infrastructure and not meant for public consumption or implementation.
  200. /// No guarantees are made about forward compatibility of the type's functionality and its usage.
  201. /// </remarks>
  202. [EditorBrowsable(EditorBrowsableState.Never)]
  203. public class SystemClockChangedEventArgs : EventArgs
  204. {
  205. /// <summary>
  206. /// Creates a new system clock notification object with unknown old and new times.
  207. /// </summary>
  208. public SystemClockChangedEventArgs()
  209. : this(DateTimeOffset.MinValue, DateTimeOffset.MaxValue)
  210. {
  211. }
  212. /// <summary>
  213. /// Creates a new system clock notification object with the specified old and new times.
  214. /// </summary>
  215. /// <param name="oldTime">Time before the system clock changed, or DateTimeOffset.MinValue if not known.</param>
  216. /// <param name="newTime">Time after the system clock changed, or DateTimeOffset.MaxValue if not known.</param>
  217. public SystemClockChangedEventArgs(DateTimeOffset oldTime, DateTimeOffset newTime)
  218. {
  219. OldTime = oldTime;
  220. NewTime = newTime;
  221. }
  222. /// <summary>
  223. /// Gets the time before the system clock changed, or DateTimeOffset.MinValue if not known.
  224. /// </summary>
  225. public DateTimeOffset OldTime { get; private set; }
  226. /// <summary>
  227. /// Gets the time after the system clock changed, or DateTimeOffset.MaxValue if not known.
  228. /// </summary>
  229. public DateTimeOffset NewTime { get; private set; }
  230. }
  231. #if NO_WEAKREFOFT
  232. class WeakReference<T>
  233. where T : class
  234. {
  235. private readonly WeakReference _weakReference;
  236. public WeakReference(T value)
  237. {
  238. _weakReference = new WeakReference(value);
  239. }
  240. public bool TryGetTarget(out T value)
  241. {
  242. value = (T)_weakReference.Target;
  243. return value != null;
  244. }
  245. }
  246. #endif
  247. #if NO_HASHSET
  248. class HashSet<T> : IEnumerable<T>
  249. {
  250. private readonly Dictionary<T, object> _dictionary = new Dictionary<T, object>();
  251. public int Count
  252. {
  253. get
  254. {
  255. return _dictionary.Count;
  256. }
  257. }
  258. public IEnumerator<T> GetEnumerator()
  259. {
  260. return _dictionary.Keys.GetEnumerator();
  261. }
  262. public void Add(T value)
  263. {
  264. _dictionary.Add(value, null);
  265. }
  266. public void Remove(T value)
  267. {
  268. _dictionary.Remove(value);
  269. }
  270. IEnumerator IEnumerable.GetEnumerator()
  271. {
  272. return GetEnumerator();
  273. }
  274. }
  275. #endif
  276. }