1
0

ConcurrencyAbstractionLayerImpl.cs 13 KB

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