Debian Codegraph @

external/rx/Rx/NET/Source/System.Reactive.PlatformServices/Reactive/Concurrency/ConcurrencyAbstractionLayerImpl.cs

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