ConcurrencyAbstractionLayer.Default.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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 DefaultConcurrencyAbstractionLayer/*Impl*/ : 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 DefaultStopwatch();
  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. #if !NO_HASHSET
  223. private static readonly HashSet<System.Threading.Timer> s_timers = new HashSet<System.Threading.Timer>();
  224. #else
  225. private static readonly Dictionary<System.Threading.Timer, object> s_timers = new Dictionary<System.Threading.Timer, object>();
  226. #endif
  227. private Action<object> _action;
  228. private System.Threading.Timer _timer;
  229. private bool _hasAdded;
  230. private bool _hasRemoved;
  231. public Timer(Action<object> action, object state, TimeSpan dueTime)
  232. {
  233. _action = action;
  234. _timer = new System.Threading.Timer(Tick, state, dueTime, TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite));
  235. lock (s_timers)
  236. {
  237. if (!_hasRemoved)
  238. {
  239. #if !NO_HASHSET
  240. s_timers.Add(_timer);
  241. #else
  242. s_timers.Add(_timer, null);
  243. #endif
  244. _hasAdded = true;
  245. }
  246. }
  247. }
  248. private void Tick(object state)
  249. {
  250. try
  251. {
  252. _action(state);
  253. }
  254. finally
  255. {
  256. Dispose();
  257. }
  258. }
  259. public void Dispose()
  260. {
  261. _action = Stubs<object>.Ignore;
  262. var timer = default(System.Threading.Timer);
  263. lock (s_timers)
  264. {
  265. if (!_hasRemoved)
  266. {
  267. timer = _timer;
  268. _timer = null;
  269. if (_hasAdded && timer != null)
  270. s_timers.Remove(timer);
  271. _hasRemoved = true;
  272. }
  273. }
  274. if (timer != null)
  275. timer.Dispose();
  276. }
  277. }
  278. class PeriodicTimer : IDisposable
  279. {
  280. //
  281. // Note: the dictionary exists to "root" the timers so that they are not garbage collected and finalized while they are running.
  282. //
  283. #if !NO_HASHSET
  284. private static readonly HashSet<System.Threading.Timer> s_timers = new HashSet<System.Threading.Timer>();
  285. #else
  286. private static readonly Dictionary<System.Threading.Timer, object> s_timers = new Dictionary<System.Threading.Timer, object>();
  287. #endif
  288. private Action _action;
  289. private System.Threading.Timer _timer;
  290. public PeriodicTimer(Action action, TimeSpan period)
  291. {
  292. _action = action;
  293. _timer = new System.Threading.Timer(Tick, null, period, period);
  294. lock (s_timers)
  295. {
  296. #if !NO_HASHSET
  297. s_timers.Add(_timer);
  298. #else
  299. s_timers.Add(_timer, null);
  300. #endif
  301. }
  302. }
  303. private void Tick(object state)
  304. {
  305. _action();
  306. }
  307. public void Dispose()
  308. {
  309. var timer = default(System.Threading.Timer);
  310. lock (s_timers)
  311. {
  312. timer = _timer;
  313. _timer = null;
  314. if (timer != null)
  315. s_timers.Remove(timer);
  316. }
  317. if (timer != null)
  318. {
  319. timer.Dispose();
  320. _action = Stubs.Nop;
  321. }
  322. }
  323. }
  324. #endif
  325. class FastPeriodicTimer : IDisposable
  326. {
  327. private readonly Action _action;
  328. private volatile bool disposed;
  329. public FastPeriodicTimer(Action action)
  330. {
  331. _action = action;
  332. new System.Threading.Thread(Loop)
  333. {
  334. Name = "Rx-FastPeriodicTimer",
  335. IsBackground = true
  336. }
  337. .Start();
  338. }
  339. private void Loop()
  340. {
  341. while (!disposed)
  342. {
  343. _action();
  344. }
  345. }
  346. public void Dispose()
  347. {
  348. disposed = true;
  349. }
  350. }
  351. }
  352. }
  353. #else
  354. using System;
  355. using System.Reactive.Disposables;
  356. using System.Threading;
  357. using System.Threading.Tasks;
  358. namespace System.Reactive.Concurrency
  359. {
  360. internal class DefaultConcurrencyAbstractionLayer : IConcurrencyAbstractionLayer
  361. {
  362. public IDisposable StartTimer(Action<object> action, object state, TimeSpan dueTime)
  363. {
  364. var cancel = new CancellationDisposable();
  365. TaskHelpers.Delay(dueTime, cancel.Token).ContinueWith(
  366. _ => action(state),
  367. TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion
  368. );
  369. return cancel;
  370. }
  371. public IDisposable StartPeriodicTimer(Action action, TimeSpan period)
  372. {
  373. if (period <= TimeSpan.Zero)
  374. {
  375. return new FastPeriodicTimer(action);
  376. }
  377. else
  378. {
  379. var cancel = new CancellationDisposable();
  380. var moveNext = default(Action);
  381. moveNext = () =>
  382. {
  383. TaskHelpers.Delay(period, cancel.Token).ContinueWith(
  384. _ =>
  385. {
  386. moveNext();
  387. action();
  388. },
  389. TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion
  390. );
  391. };
  392. moveNext();
  393. return cancel;
  394. }
  395. }
  396. public IDisposable QueueUserWorkItem(Action<object> action, object state)
  397. {
  398. var cancel = new CancellationDisposable();
  399. Task.Factory.StartNew(action, state, cancel.Token);
  400. return cancel;
  401. }
  402. public void Sleep(TimeSpan timeout)
  403. {
  404. TaskHelpers.Delay(timeout, CancellationToken.None).Wait();
  405. }
  406. public IStopwatch StartStopwatch()
  407. {
  408. return new DefaultStopwatch();
  409. }
  410. public bool SupportsLongRunning
  411. {
  412. get { return true; }
  413. }
  414. public void StartThread(Action<object> action, object state)
  415. {
  416. Task.Factory.StartNew(() =>
  417. {
  418. action(state);
  419. }, TaskCreationOptions.LongRunning);
  420. }
  421. class FastPeriodicTimer : IDisposable
  422. {
  423. private readonly Action _action;
  424. private bool disposed;
  425. public FastPeriodicTimer(Action action)
  426. {
  427. _action = action;
  428. Task.Factory.StartNew(Loop, TaskCreationOptions.LongRunning);
  429. }
  430. private void Loop()
  431. {
  432. while (!disposed)
  433. {
  434. _action();
  435. }
  436. }
  437. public void Dispose()
  438. {
  439. disposed = true;
  440. }
  441. }
  442. }
  443. }
  444. #endif