SystemClock.cs 10.0 KB

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