Debian Codegraph @

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