1
0

ConcurrencyAbstractionLayerImpl.cs 8.8 KB

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