ConcurrencyAbstractionLayerImpl.cs 12 KB

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