ConcurrencyAbstractionLayerImpl.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. #if !NO_THREAD
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Reactive.Disposables;
  8. using System.Threading;
  9. namespace System.Reactive.Concurrency
  10. {
  11. //
  12. // WARNING: This code is kept *identically* in two places. One copy is kept in System.Reactive.Core for non-PLIB platforms.
  13. // Another copy is kept in System.Reactive.PlatformServices to enlighten the default lowest common denominator
  14. // behavior of Rx for PLIB when used on a more capable platform.
  15. //
  16. internal class /*Default*/ConcurrencyAbstractionLayerImpl : IConcurrencyAbstractionLayer
  17. {
  18. public IDisposable StartTimer(Action<object> action, object state, TimeSpan dueTime)
  19. {
  20. return new Timer(action, state, Normalize(dueTime));
  21. }
  22. public IDisposable StartPeriodicTimer(Action action, TimeSpan period)
  23. {
  24. if (period < TimeSpan.Zero)
  25. throw new ArgumentOutOfRangeException(nameof(period));
  26. //
  27. // The contract for periodic scheduling in Rx is that specifying TimeSpan.Zero as the period causes the scheduler to
  28. // call back periodically as fast as possible, sequentially.
  29. //
  30. if (period == TimeSpan.Zero)
  31. {
  32. return new FastPeriodicTimer(action);
  33. }
  34. else
  35. {
  36. return new PeriodicTimer(action, period);
  37. }
  38. }
  39. public IDisposable QueueUserWorkItem(Action<object> action, object state)
  40. {
  41. System.Threading.ThreadPool.QueueUserWorkItem(_ => action(_), state);
  42. return Disposable.Empty;
  43. }
  44. #if USE_SLEEP_MS
  45. public void Sleep(TimeSpan timeout)
  46. {
  47. System.Threading.Thread.Sleep((int)Normalize(timeout).TotalMilliseconds);
  48. }
  49. #else
  50. public void Sleep(TimeSpan timeout)
  51. {
  52. System.Threading.Thread.Sleep(Normalize(timeout));
  53. }
  54. #endif
  55. public IStopwatch StartStopwatch()
  56. {
  57. return new StopwatchImpl();
  58. }
  59. public bool SupportsLongRunning
  60. {
  61. get { return true; }
  62. }
  63. public void StartThread(Action<object> action, object state)
  64. {
  65. new Thread(() =>
  66. {
  67. action(state);
  68. }) { IsBackground = true }.Start();
  69. }
  70. private static TimeSpan Normalize(TimeSpan dueTime)
  71. {
  72. if (dueTime < TimeSpan.Zero)
  73. return TimeSpan.Zero;
  74. return dueTime;
  75. }
  76. #if USE_TIMER_SELF_ROOT
  77. //
  78. // Some historical context. In the early days of Rx, we discovered an issue with
  79. // the rooting of timers, causing them to get GC'ed even when the IDisposable of
  80. // a scheduled activity was kept alive. The original code simply created a timer
  81. // as follows:
  82. //
  83. // var t = default(Timer);
  84. // t = new Timer(_ =>
  85. // {
  86. // t = null;
  87. // Debug.WriteLine("Hello!");
  88. // }, null, 5000, Timeout.Infinite);
  89. //
  90. // IIRC the reference to "t" captured by the closure wasn't sufficient on .NET CF
  91. // to keep the timer rooted, causing problems on Windows Phone 7. As a result, we
  92. // added rooting code using a dictionary (SD 7280), which we carried forward all
  93. // the way to Rx v2.0 RTM.
  94. //
  95. // However, the desktop CLR's implementation of System.Threading.Timer exhibits
  96. // other characteristics where a timer can root itself when the timer is still
  97. // reachable through the state or callback parameters. To illustrate this, run
  98. // the following piece of code:
  99. //
  100. // static void Main()
  101. // {
  102. // Bar();
  103. //
  104. // while (true)
  105. // {
  106. // GC.Collect();
  107. // GC.WaitForPendingFinalizers();
  108. // Thread.Sleep(100);
  109. // }
  110. // }
  111. //
  112. // static void Bar()
  113. // {
  114. // var t = default(Timer);
  115. // t = new Timer(_ =>
  116. // {
  117. // t = null; // Comment out this line to see the timer stop
  118. // Console.WriteLine("Hello!");
  119. // }, null, 5000, Timeout.Infinite);
  120. // }
  121. //
  122. // When the closure over "t" is removed, the timer will stop automatically upon
  123. // garbage collection. However, when retaining the reference, this problem does
  124. // not exist. The code below exploits this behavior, avoiding unnecessary costs
  125. // to root timers in a thread-safe manner.
  126. //
  127. // Below is a fragment of SOS output, proving the proper rooting:
  128. //
  129. // !gcroot 02492440
  130. // HandleTable:
  131. // 005a13fc (pinned handle)
  132. // -> 03491010 System.Object[]
  133. // -> 024924dc System.Threading.TimerQueue
  134. // -> 02492450 System.Threading.TimerQueueTimer
  135. // -> 02492420 System.Threading.TimerCallback
  136. // -> 02492414 TimerRootingExperiment.Program+<>c__DisplayClass1
  137. // -> 02492440 System.Threading.Timer
  138. //
  139. // With the USE_TIMER_SELF_ROOT symbol, we shake off this additional rooting code
  140. // for newer platforms where this no longer needed. We checked this on .NET Core
  141. // as well as .NET 4.0, and only #define this symbol for those platforms.
  142. //
  143. class Timer : IDisposable
  144. {
  145. private Action<object> _action;
  146. private volatile System.Threading.Timer _timer;
  147. public Timer(Action<object> action, object state, TimeSpan dueTime)
  148. {
  149. _action = action;
  150. // Don't want the spin wait in Tick to get stuck if this thread gets aborted.
  151. try { }
  152. finally
  153. {
  154. //
  155. // Rooting of the timer happens through the this.Tick delegate's target object,
  156. // which is the current instance and has a field to store the Timer instance.
  157. //
  158. _timer = new System.Threading.Timer(this.Tick, state, dueTime, TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite));
  159. }
  160. }
  161. private void Tick(object state)
  162. {
  163. try
  164. {
  165. _action(state);
  166. }
  167. finally
  168. {
  169. SpinWait.SpinUntil(IsTimerAssigned);
  170. Dispose();
  171. }
  172. }
  173. private bool IsTimerAssigned()
  174. {
  175. return _timer != null;
  176. }
  177. public void Dispose()
  178. {
  179. var timer = _timer;
  180. if (timer != TimerStubs.Never)
  181. {
  182. _action = Stubs<object>.Ignore;
  183. _timer = TimerStubs.Never;
  184. timer.Dispose();
  185. }
  186. }
  187. }
  188. class PeriodicTimer : IDisposable
  189. {
  190. private Action _action;
  191. private volatile System.Threading.Timer _timer;
  192. public PeriodicTimer(Action action, TimeSpan period)
  193. {
  194. _action = action;
  195. //
  196. // Rooting of the timer happens through the this.Tick delegate's target object,
  197. // which is the current instance and has a field to store the Timer instance.
  198. //
  199. _timer = new System.Threading.Timer(this.Tick, null, period, period);
  200. }
  201. private void Tick(object state)
  202. {
  203. _action();
  204. }
  205. public void Dispose()
  206. {
  207. var timer = _timer;
  208. if (timer != null)
  209. {
  210. _action = Stubs.Nop;
  211. _timer = null;
  212. timer.Dispose();
  213. }
  214. }
  215. }
  216. #else
  217. class Timer : IDisposable
  218. {
  219. //
  220. // Note: the dictionary exists to "root" the timers so that they are not garbage collected and finalized while they are running.
  221. //
  222. private static readonly HashSet<System.Threading.Timer> s_timers = new HashSet<System.Threading.Timer>();
  223. private Action<object> _action;
  224. private System.Threading.Timer _timer;
  225. private bool _hasAdded;
  226. private bool _hasRemoved;
  227. public Timer(Action<object> action, object state, TimeSpan dueTime)
  228. {
  229. _action = action;
  230. _timer = new System.Threading.Timer(Tick, state, dueTime, TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite));
  231. lock (s_timers)
  232. {
  233. if (!_hasRemoved)
  234. {
  235. s_timers.Add(_timer);
  236. _hasAdded = true;
  237. }
  238. }
  239. }
  240. private void Tick(object state)
  241. {
  242. try
  243. {
  244. _action(state);
  245. }
  246. finally
  247. {
  248. Dispose();
  249. }
  250. }
  251. public void Dispose()
  252. {
  253. _action = Stubs<object>.Ignore;
  254. var timer = default(System.Threading.Timer);
  255. lock (s_timers)
  256. {
  257. if (!_hasRemoved)
  258. {
  259. timer = _timer;
  260. _timer = null;
  261. if (_hasAdded && timer != null)
  262. s_timers.Remove(timer);
  263. _hasRemoved = true;
  264. }
  265. }
  266. if (timer != null)
  267. timer.Dispose();
  268. }
  269. }
  270. class PeriodicTimer : IDisposable
  271. {
  272. //
  273. // Note: the dictionary exists to "root" the timers so that they are not garbage collected and finalized while they are running.
  274. //
  275. private static readonly HashSet<System.Threading.Timer> s_timers = new HashSet<System.Threading.Timer>();
  276. private Action _action;
  277. private System.Threading.Timer _timer;
  278. public PeriodicTimer(Action action, TimeSpan period)
  279. {
  280. _action = action;
  281. _timer = new System.Threading.Timer(Tick, null, period, period);
  282. lock (s_timers)
  283. {
  284. s_timers.Add(_timer);
  285. }
  286. }
  287. private void Tick(object state)
  288. {
  289. _action();
  290. }
  291. public void Dispose()
  292. {
  293. var timer = default(System.Threading.Timer);
  294. lock (s_timers)
  295. {
  296. timer = _timer;
  297. _timer = null;
  298. if (timer != null)
  299. s_timers.Remove(timer);
  300. }
  301. if (timer != null)
  302. {
  303. timer.Dispose();
  304. _action = Stubs.Nop;
  305. }
  306. }
  307. }
  308. #endif
  309. class FastPeriodicTimer : IDisposable
  310. {
  311. private readonly Action _action;
  312. private volatile bool disposed;
  313. public FastPeriodicTimer(Action action)
  314. {
  315. _action = action;
  316. new System.Threading.Thread(Loop)
  317. {
  318. Name = "Rx-FastPeriodicTimer",
  319. IsBackground = true
  320. }
  321. .Start();
  322. }
  323. private void Loop()
  324. {
  325. while (!disposed)
  326. {
  327. _action();
  328. }
  329. }
  330. public void Dispose()
  331. {
  332. disposed = true;
  333. }
  334. }
  335. }
  336. }
  337. #endif