ConcurrencyAbstractionLayer.Default.cs 14 KB

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