Debian Codegraph @

external/rx/Rx/NET/Source/System.Reactive.PlatformServices/Reactive/Concurrency/ThreadPoolScheduler.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 !WINDOWS && !NO_THREAD
4 using System.Collections.Generic;
5 using System.Reactive.Disposables;
6 using System.Threading;
7
8 namespace System.Reactive.Concurrency
9 {
10 /// <summary>
11 /// Represents an object that schedules units of work on the CLR thread pool.
12 /// </summary>
13 /// <seealso cref="ThreadPoolScheduler.Instance">Singleton instance of this type exposed through this static property.</seealso>
14 public sealed class ThreadPoolScheduler : LocalScheduler, ISchedulerLongRunning, ISchedulerPeriodic
15 {
16 private static readonly ThreadPoolScheduler s_instance = new ThreadPoolScheduler();
17
18 /// <summary>
19 /// Gets the singleton instance of the CLR thread pool scheduler.
20 /// </summary>
21 public static ThreadPoolScheduler Instance
22 {
23 get
24 {
25 return s_instance;
26 }
27 }
28
29 ThreadPoolScheduler()
30 {
31 }
32
33 /// <summary>
34 /// Schedules an action to be executed.
35 /// </summary>
36 /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
37 /// <param name="state">State passed to the action to be executed.</param>
38 /// <param name="action">Action to be executed.</param>
39 /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
40 /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
41 public override IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
42 {
43 if (action == null)
44 throw new ArgumentNullException("action");
45
46 var d = new SingleAssignmentDisposable();
47
48 ThreadPool.QueueUserWorkItem(_ =>
49 {
50 if (!d.IsDisposed)
51 d.Disposable = action(this, state);
52 }, null);
53
54 return d;
55 }
56
57 /// <summary>
58 /// Schedules an action to be executed after dueTime, using a System.Threading.Timer object.
59 /// </summary>
60 /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
61 /// <param name="state">State passed to the action to be executed.</param>
62 /// <param name="action">Action to be executed.</param>
63 /// <param name="dueTime">Relative time after which to execute the action.</param>
64 /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
65 /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
66 public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
67 {
68 if (action == null)
69 throw new ArgumentNullException("action");
70
71 var dt = Scheduler.Normalize(dueTime);
72 if (dt.Ticks == 0)
73 return Schedule(state, action);
74
75 return new Timer<TState>(this, state, dt, action);
76 }
77
78 /// <summary>
79 /// Schedules a long-running task by creating a new thread. Cancellation happens through polling.
80 /// </summary>
81 /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
82 /// <param name="state">State passed to the action to be executed.</param>
83 /// <param name="action">Action to be executed.</param>
84 /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
85 /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
86 public IDisposable ScheduleLongRunning<TState>(TState state, Action<TState, ICancelable> action)
87 {
88 if (action == null)
89 throw new ArgumentNullException("action");
90
91 return NewThreadScheduler.Default.ScheduleLongRunning(state, action);
92 }
93
94 #if !NO_STOPWATCH
95 /// <summary>
96 /// Starts a new stopwatch object.
97 /// </summary>
98 /// <returns>New stopwatch object; started at the time of the request.</returns>
99 public override IStopwatch StartStopwatch()
100 {
101 //
102 // Strictly speaking, this explicit override is not necessary because the base implementation calls into
103 // the enlightenment module to obtain the CAL, which would circle back to System.Reactive.PlatformServices
104 // where we're currently running. This is merely a short-circuit to avoid the additional roundtrip.
105 //
106 return new StopwatchImpl();
107 }
108 #endif
109
110 /// <summary>
111 /// Schedules a periodic piece of work, using a System.Threading.Timer object.
112 /// </summary>
113 /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
114 /// <param name="state">Initial state passed to the action upon the first iteration.</param>
115 /// <param name="period">Period for running the work periodically.</param>
116 /// <param name="action">Action to be executed, potentially updating the state.</param>
117 /// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns>
118 /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
119 /// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than or equal to zero.</exception>
120 public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action)
121 {
122 //
123 // MSDN documentation states the following:
124 //
125 // "If period is zero (0) or negative one (-1) milliseconds and dueTime is positive, callback is invoked once;
126 // the periodic behavior of the timer is disabled, but can be re-enabled using the Change method."
127 //
128 if (period <= TimeSpan.Zero)
129 throw new ArgumentOutOfRangeException("period");
130 if (action == null)
131 throw new ArgumentNullException("action");
132
133 return new PeriodicTimer<TState>(state, period, action);
134 }
135
136 #if USE_TIMER_SELF_ROOT
137
138 //
139 // See ConcurrencyAbstractionLayerImpl.cs for more information about the code
140 // below and its timer rooting behavior.
141 //
142
143 sealed class Timer<TState> : IDisposable
144 {
145 private readonly MultipleAssignmentDisposable _disposable;
146
147 private readonly IScheduler _parent;
148 private readonly TState _state;
149 private Func<IScheduler, TState, IDisposable> _action;
150
151 private volatile System.Threading.Timer _timer;
152
153 public Timer(IScheduler parent, TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
154 {
155 _parent = parent;
156 _state = state;
157 _action = action;
158
159 _disposable = new MultipleAssignmentDisposable();
160 _disposable.Disposable = Disposable.Create(Stop);
161
162 // Don't want the spin wait in Tick to get stuck if this thread gets aborted.
163 try { }
164 finally
165 {
166 //
167 // Rooting of the timer happens through the this.Tick delegate's target object,
168 // which is the current instance and has a field to store the Timer instance.
169 //
170 _timer = new System.Threading.Timer(this.Tick, null, dueTime, TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite));
171 }
172 }
173
174 private void Tick(object state)
175 {
176 try
177 {
178 _disposable.Disposable = _action(_parent, _state);
179 }
180 finally
181 {
182 SpinWait.SpinUntil(IsTimerAssigned);
183 Stop();
184 }
185 }
186
187 private bool IsTimerAssigned()
188 {
189 return _timer != null;
190 }
191
192 public void Dispose()
193 {
194 _disposable.Dispose();
195 }
196
197 private void Stop()
198 {
199 var timer = _timer;
200 if (timer != TimerStubs.Never)
201 {
202 _action = Nop;
203 _timer = TimerStubs.Never;
204
205 timer.Dispose();
206 }
207 }
208
209 private IDisposable Nop(IScheduler scheduler, TState state)
210 {
211 return Disposable.Empty;
212 }
213 }
214
215 sealed class PeriodicTimer<TState> : IDisposable
216 {
217 private TState _state;
218 private Func<TState, TState> _action;
219
220 private readonly AsyncLock _gate;
221 private volatile System.Threading.Timer _timer;
222
223 public PeriodicTimer(TState state, TimeSpan period, Func<TState, TState> action)
224 {
225 _state = state;
226 _action = action;
227
228 _gate = new AsyncLock();
229
230 //
231 // Rooting of the timer happens through the this.Tick delegate's target object,
232 // which is the current instance and has a field to store the Timer instance.
233 //
234 _timer = new System.Threading.Timer(this.Tick, null, period, period);
235 }
236
237 private void Tick(object state)
238 {
239 _gate.Wait(() =>
240 {
241 _state = _action(_state);
242 });
243 }
244
245 public void Dispose()
246 {
247 var timer = _timer;
248 if (timer != null)
249 {
250 _action = Stubs<TState>.I;
251 _timer = null;
252
253 timer.Dispose();
254 _gate.Dispose();
255 }
256 }
257 }
258 #else
259 abstract class Timer
260 {
261 //
262 // Note: the dictionary exists to "root" the timers so that they are not garbage collected and finalized while they are running.
263 //
264 #if !NO_HASHSET
265 protected static readonly HashSet<System.Threading.Timer> s_timers = new HashSet<System.Threading.Timer>();
266 #else
267 protected static readonly Dictionary<System.Threading.Timer, object> s_timers = new Dictionary<System.Threading.Timer, object>();
268 #endif
269 }
270
271 sealed class Timer<TState> : Timer, IDisposable
272 {
273 private readonly MultipleAssignmentDisposable _disposable;
274
275 private readonly IScheduler _parent;
276 private readonly TState _state;
277
278 private Func<IScheduler, TState, IDisposable> _action;
279 private System.Threading.Timer _timer;
280
281 private bool _hasAdded;
282 private bool _hasRemoved;
283
284 public Timer(IScheduler parent, TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
285 {
286 _disposable = new MultipleAssignmentDisposable();
287 _disposable.Disposable = Disposable.Create(Unroot);
288
289 _parent = parent;
290 _state = state;
291
292 _action = action;
293 _timer = new System.Threading.Timer(Tick, null, dueTime, TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite));
294
295 lock (s_timers)
296 {
297 if (!_hasRemoved)
298 {
299 #if !NO_HASHSET
300 s_timers.Add(_timer);
301 #else
302 s_timers.Add(_timer, null);
303 #endif
304
305 _hasAdded = true;
306 }
307 }
308 }
309
310 private void Tick(object state)
311 {
312 try
313 {
314 _disposable.Disposable = _action(_parent, _state);
315 }
316 finally
317 {
318 Unroot();
319 }
320 }
321
322 private void Unroot()
323 {
324 _action = Nop;
325
326 var timer = default(System.Threading.Timer);
327
328 lock (s_timers)
329 {
330 if (!_hasRemoved)
331 {
332 timer = _timer;
333 _timer = null;
334
335 if (_hasAdded && timer != null)
336 s_timers.Remove(timer);
337
338 _hasRemoved = true;
339 }
340 }
341
342 if (timer != null)
343 timer.Dispose();
344 }
345
346 private IDisposable Nop(IScheduler scheduler, TState state)
347 {
348 return Disposable.Empty;
349 }
350
351 public void Dispose()
352 {
353 _disposable.Dispose();
354 }
355 }
356
357 abstract class PeriodicTimer
358 {
359 //
360 // Note: the dictionary exists to "root" the timers so that they are not garbage collected and finalized while they are running.
361 //
362 #if !NO_HASHSET
363 protected static readonly HashSet<System.Threading.Timer> s_timers = new HashSet<System.Threading.Timer>();
364 #else
365 protected static readonly Dictionary<System.Threading.Timer, object> s_timers = new Dictionary<System.Threading.Timer, object>();
366 #endif
367 }
368
369 sealed class PeriodicTimer<TState> : PeriodicTimer, IDisposable
370 {
371 private readonly AsyncLock _gate;
372
373 private TState _state;
374 private Func<TState, TState> _action;
375 private System.Threading.Timer _timer;
376
377 public PeriodicTimer(TState state, TimeSpan period, Func<TState, TState> action)
378 {
379 _gate = new AsyncLock();
380
381 _state = state;
382 _action = action;
383 _timer = new System.Threading.Timer(Tick, null, period, period);
384
385 lock (s_timers)
386 {
387 #if !NO_HASHSET
388 s_timers.Add(_timer);
389 #else
390 s_timers.Add(_timer, null);
391 #endif
392 }
393 }
394
395 private void Tick(object state)
396 {
397 _gate.Wait(() =>
398 {
399 _state = _action(_state);
400 });
401 }
402
403 public void Dispose()
404 {
405 var timer = default(System.Threading.Timer);
406
407 lock (s_timers)
408 {
409 timer = _timer;
410 _timer = null;
411
412 if (timer != null)
413 s_timers.Remove(timer);
414 }
415
416 if (timer != null)
417 {
418 timer.Dispose();
419 _gate.Dispose();
420 _action = Stubs<TState>.I;
421 }
422 }
423 }
424 #endif
425 }
426 }
427 #endif