ConcurrencyAbstractionLayer.Default.cs 15 KB

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