SystemClock.cs 11 KB

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