ConcurrencyAbstractionLayerImpl.cs 13 KB

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