ConcurrencyAbstractionLayerImpl.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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.Collections.Generic;
  6. using System.Reactive.Disposables;
  7. using System.Threading;
  8. namespace System.Reactive.Concurrency
  9. {
  10. //
  11. // WARNING: This code is kept *identically* in two places. One copy is kept in System.Reactive.Core for non-PLIB platforms.
  12. // Another copy is kept in System.Reactive.PlatformServices to enlighten the default lowest common denominator
  13. // behavior of Rx for PLIB when used on a more capable platform.
  14. //
  15. internal class /*Default*/ConcurrencyAbstractionLayerImpl : IConcurrencyAbstractionLayer
  16. {
  17. public IDisposable StartTimer(Action<object> action, object state, TimeSpan dueTime) => new Timer(action, state, Normalize(dueTime));
  18. public IDisposable StartPeriodicTimer(Action action, TimeSpan period)
  19. {
  20. if (period < TimeSpan.Zero)
  21. throw new ArgumentOutOfRangeException(nameof(period));
  22. //
  23. // The contract for periodic scheduling in Rx is that specifying TimeSpan.Zero as the period causes the scheduler to
  24. // call back periodically as fast as possible, sequentially.
  25. //
  26. if (period == TimeSpan.Zero)
  27. {
  28. return new FastPeriodicTimer(action);
  29. }
  30. else
  31. {
  32. return new PeriodicTimer(action, period);
  33. }
  34. }
  35. public IDisposable QueueUserWorkItem(Action<object> action, object state)
  36. {
  37. System.Threading.ThreadPool.QueueUserWorkItem(_ => action(_), state);
  38. return Disposable.Empty;
  39. }
  40. public void Sleep(TimeSpan timeout) => System.Threading.Thread.Sleep(Normalize(timeout));
  41. public IStopwatch StartStopwatch() => new StopwatchImpl();
  42. public bool SupportsLongRunning => true;
  43. public void StartThread(Action<object> action, object state)
  44. {
  45. new Thread(() =>
  46. {
  47. action(state);
  48. }) { IsBackground = true }.Start();
  49. }
  50. private static TimeSpan Normalize(TimeSpan dueTime) => dueTime < TimeSpan.Zero ? TimeSpan.Zero : dueTime;
  51. //
  52. // Some historical context. In the early days of Rx, we discovered an issue with
  53. // the rooting of timers, causing them to get GC'ed even when the IDisposable of
  54. // a scheduled activity was kept alive. The original code simply created a timer
  55. // as follows:
  56. //
  57. // var t = default(Timer);
  58. // t = new Timer(_ =>
  59. // {
  60. // t = null;
  61. // Debug.WriteLine("Hello!");
  62. // }, null, 5000, Timeout.Infinite);
  63. //
  64. // IIRC the reference to "t" captured by the closure wasn't sufficient on .NET CF
  65. // to keep the timer rooted, causing problems on Windows Phone 7. As a result, we
  66. // added rooting code using a dictionary (SD 7280), which we carried forward all
  67. // the way to Rx v2.0 RTM.
  68. //
  69. // However, the desktop CLR's implementation of System.Threading.Timer exhibits
  70. // other characteristics where a timer can root itself when the timer is still
  71. // reachable through the state or callback parameters. To illustrate this, run
  72. // the following piece of code:
  73. //
  74. // static void Main()
  75. // {
  76. // Bar();
  77. //
  78. // while (true)
  79. // {
  80. // GC.Collect();
  81. // GC.WaitForPendingFinalizers();
  82. // Thread.Sleep(100);
  83. // }
  84. // }
  85. //
  86. // static void Bar()
  87. // {
  88. // var t = default(Timer);
  89. // t = new Timer(_ =>
  90. // {
  91. // t = null; // Comment out this line to see the timer stop
  92. // Console.WriteLine("Hello!");
  93. // }, null, 5000, Timeout.Infinite);
  94. // }
  95. //
  96. // When the closure over "t" is removed, the timer will stop automatically upon
  97. // garbage collection. However, when retaining the reference, this problem does
  98. // not exist. The code below exploits this behavior, avoiding unnecessary costs
  99. // to root timers in a thread-safe manner.
  100. //
  101. // Below is a fragment of SOS output, proving the proper rooting:
  102. //
  103. // !gcroot 02492440
  104. // HandleTable:
  105. // 005a13fc (pinned handle)
  106. // -> 03491010 System.Object[]
  107. // -> 024924dc System.Threading.TimerQueue
  108. // -> 02492450 System.Threading.TimerQueueTimer
  109. // -> 02492420 System.Threading.TimerCallback
  110. // -> 02492414 TimerRootingExperiment.Program+<>c__DisplayClass1
  111. // -> 02492440 System.Threading.Timer
  112. //
  113. // With the USE_TIMER_SELF_ROOT symbol, we shake off this additional rooting code
  114. // for newer platforms where this no longer needed. We checked this on .NET Core
  115. // as well as .NET 4.0, and only #define this symbol for those platforms.
  116. //
  117. // NB: 4/13/2017 - All target platforms for the 4.x release have the self-rooting
  118. // behavior described here, so we removed the USE_TIMER_SELF_ROOT
  119. // symbol.
  120. //
  121. private sealed class Timer : IDisposable
  122. {
  123. private Action<object> _action;
  124. private volatile System.Threading.Timer _timer;
  125. public Timer(Action<object> action, object state, TimeSpan dueTime)
  126. {
  127. _action = action;
  128. // Don't want the spin wait in Tick to get stuck if this thread gets aborted.
  129. try { }
  130. finally
  131. {
  132. //
  133. // Rooting of the timer happens through the this.Tick delegate's target object,
  134. // which is the current instance and has a field to store the Timer instance.
  135. //
  136. _timer = new System.Threading.Timer(this.Tick, state, dueTime, TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite));
  137. }
  138. }
  139. private void Tick(object state)
  140. {
  141. try
  142. {
  143. _action(state);
  144. }
  145. finally
  146. {
  147. SpinWait.SpinUntil(IsTimerAssigned);
  148. Dispose();
  149. }
  150. }
  151. private bool IsTimerAssigned() => _timer != null;
  152. public void Dispose()
  153. {
  154. var timer = _timer;
  155. if (timer != TimerStubs.Never)
  156. {
  157. _action = Stubs<object>.Ignore;
  158. _timer = TimerStubs.Never;
  159. timer.Dispose();
  160. }
  161. }
  162. }
  163. private sealed class PeriodicTimer : IDisposable
  164. {
  165. private Action _action;
  166. private volatile System.Threading.Timer _timer;
  167. public PeriodicTimer(Action action, TimeSpan period)
  168. {
  169. _action = action;
  170. //
  171. // Rooting of the timer happens through the this.Tick delegate's target object,
  172. // which is the current instance and has a field to store the Timer instance.
  173. //
  174. _timer = new System.Threading.Timer(this.Tick, null, period, period);
  175. }
  176. private void Tick(object state) => _action();
  177. public void Dispose()
  178. {
  179. var timer = _timer;
  180. if (timer != null)
  181. {
  182. _action = Stubs.Nop;
  183. _timer = null;
  184. timer.Dispose();
  185. }
  186. }
  187. }
  188. private sealed class FastPeriodicTimer : IDisposable
  189. {
  190. private readonly Action _action;
  191. private volatile bool disposed;
  192. public FastPeriodicTimer(Action action)
  193. {
  194. _action = action;
  195. new System.Threading.Thread(Loop)
  196. {
  197. Name = "Rx-FastPeriodicTimer",
  198. IsBackground = true
  199. }
  200. .Start();
  201. }
  202. private void Loop()
  203. {
  204. while (!disposed)
  205. {
  206. _action();
  207. }
  208. }
  209. public void Dispose()
  210. {
  211. disposed = true;
  212. }
  213. }
  214. }
  215. }
  216. #endif