Debian Codegraph @

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

raw
1 // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
2
3 using System.Collections.Generic;
4 using System.Reactive.Disposables;
5 using System.Threading;
6
7 #if NO_SEMAPHORE
8 using System.Reactive.Threading;
9 #endif
10
11 namespace System.Reactive.Concurrency
12 {
13 /// <summary>
14 /// Represents an object that schedules units of work on a designated thread.
15 /// </summary>
16 public sealed class EventLoopScheduler : LocalScheduler, ISchedulerPeriodic, IDisposable
17 {
18 #region Fields
19
20 /// <summary>
21 /// Counter for diagnostic purposes, to name the threads.
22 /// </summary>
23 private static int s_counter;
24
25 /// <summary>
26 /// Thread factory function.
27 /// </summary>
28 private readonly Func<ThreadStart, Thread> _threadFactory;
29
30 /// <summary>
31 /// Stopwatch for timing free of absolute time dependencies.
32 /// </summary>
33 private IStopwatch _stopwatch;
34
35 /// <summary>
36 /// Thread used by the event loop to run work items on. No work should be run on any other thread.
37 /// If ExitIfEmpty is set, the thread can quit and a new thread will be created when new work is scheduled.
38 /// </summary>
39 private Thread _thread;
40
41 /// <summary>
42 /// Gate to protect data structures, including the work queue and the ready list.
43 /// </summary>
44 private readonly object _gate;
45
46 /// <summary>
47 /// Semaphore to count requests to re-evaluate the queue, from either Schedule requests or when a timer
48 /// expires and moves on to the next item in the queue.
49 /// </summary>
50 #if !NO_CDS
51 private readonly SemaphoreSlim _evt;
52 #else
53 private readonly Semaphore _evt;
54 #endif
55
56 /// <summary>
57 /// Queue holding work items. Protected by the gate.
58 /// </summary>
59 private readonly SchedulerQueue<TimeSpan> _queue;
60
61 /// <summary>
62 /// Queue holding items that are ready to be run as soon as possible. Protected by the gate.
63 /// </summary>
64 private readonly Queue<ScheduledItem<TimeSpan>> _readyList;
65
66 /// <summary>
67 /// Work item that will be scheduled next. Used upon reevaluation of the queue to check whether the next
68 /// item is still the same. If not, a new timer needs to be started (see below).
69 /// </summary>
70 private ScheduledItem<TimeSpan> _nextItem;
71
72 /// <summary>
73 /// Disposable that always holds the timer to dispatch the first element in the queue.
74 /// </summary>
75 private readonly SerialDisposable _nextTimer;
76
77 /// <summary>
78 /// Flag indicating whether the event loop should quit. When set, the event should be signaled as well to
79 /// wake up the event loop thread, which will subsequently abandon all work.
80 /// </summary>
81 private bool _disposed;
82
83 #endregion
84
85 #region Constructors
86
87 /// <summary>
88 /// Creates an object that schedules units of work on a designated thread.
89 /// </summary>
90 public EventLoopScheduler()
91 : this(a => new Thread(a) { Name = "Event Loop " + Interlocked.Increment(ref s_counter), IsBackground = true })
92 {
93 }
94
95 #if !NO_THREAD
96 /// <summary>
97 /// Creates an object that schedules units of work on a designated thread, using the specified factory to control thread creation options.
98 /// </summary>
99 /// <param name="threadFactory">Factory function for thread creation.</param>
100 /// <exception cref="ArgumentNullException"><paramref name="threadFactory"/> is null.</exception>
101 public EventLoopScheduler(Func<ThreadStart, Thread> threadFactory)
102 {
103 if (threadFactory == null)
104 throw new ArgumentNullException("threadFactory");
105 #else
106 internal EventLoopScheduler(Func<ThreadStart, Thread> threadFactory)
107 {
108 #endif
109 _threadFactory = threadFactory;
110 _stopwatch = ConcurrencyAbstractionLayer.Current.StartStopwatch();
111
112 _gate = new object();
113
114 #if !NO_CDS
115 _evt = new SemaphoreSlim(0);
116 #else
117 _evt = new Semaphore(0, int.MaxValue);
118 #endif
119 _queue = new SchedulerQueue<TimeSpan>();
120 _readyList = new Queue<ScheduledItem<TimeSpan>>();
121
122 _nextTimer = new SerialDisposable();
123
124 ExitIfEmpty = false;
125 }
126
127 #endregion
128
129 #region Properties
130
131 /// <summary>
132 /// Indicates whether the event loop thread is allowed to quit when no work is left. If new work
133 /// is scheduled afterwards, a new event loop thread is created. This property is used by the
134 /// NewThreadScheduler which uses an event loop for its recursive invocations.
135 /// </summary>
136 internal bool ExitIfEmpty
137 {
138 get;
139 set;
140 }
141
142 #endregion
143
144 #region Public methods
145
146 /// <summary>
147 /// Schedules an action to be executed after dueTime.
148 /// </summary>
149 /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
150 /// <param name="state">State passed to the action to be executed.</param>
151 /// <param name="action">Action to be executed.</param>
152 /// <param name="dueTime">Relative time after which to execute the action.</param>
153 /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
154 /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
155 /// <exception cref="ObjectDisposedException">The scheduler has been disposed and doesn't accept new work.</exception>
156 public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
157 {
158 if (action == null)
159 throw new ArgumentNullException("action");
160
161 var due = _stopwatch.Elapsed + dueTime;
162 var si = new ScheduledItem<TimeSpan, TState>(this, state, action, due);
163
164 lock (_gate)
165 {
166 if (_disposed)
167 throw new ObjectDisposedException("");
168
169 if (dueTime <= TimeSpan.Zero)
170 {
171 _readyList.Enqueue(si);
172 _evt.Release();
173 }
174 else
175 {
176 _queue.Enqueue(si);
177 _evt.Release();
178 }
179
180 EnsureThread();
181 }
182
183 return Disposable.Create(si.Cancel);
184 }
185
186 /// <summary>
187 /// Schedules a periodic piece of work on the designated thread.
188 /// </summary>
189 /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
190 /// <param name="state">Initial state passed to the action upon the first iteration.</param>
191 /// <param name="period">Period for running the work periodically.</param>
192 /// <param name="action">Action to be executed, potentially updating the state.</param>
193 /// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns>
194 /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
195 /// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than TimeSpan.Zero.</exception>
196 /// <exception cref="ObjectDisposedException">The scheduler has been disposed and doesn't accept new work.</exception>
197 public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action)
198 {
199 if (period < TimeSpan.Zero)
200 throw new ArgumentOutOfRangeException("period");
201 if (action == null)
202 throw new ArgumentNullException("action");
203
204 var start = _stopwatch.Elapsed;
205 var next = start + period;
206
207 var state1 = state;
208
209 var d = new MultipleAssignmentDisposable();
210 var gate = new AsyncLock();
211
212 var tick = default(Func<IScheduler, object, IDisposable>);
213 tick = (self_, _) =>
214 {
215 next += period;
216
217 d.Disposable = self_.Schedule(null, next - _stopwatch.Elapsed, tick);
218
219 gate.Wait(() =>
220 {
221 state1 = action(state1);
222 });
223
224 return Disposable.Empty;
225 };
226
227 d.Disposable = Schedule(null, next - _stopwatch.Elapsed, tick);
228
229 return new CompositeDisposable(d, gate);
230 }
231
232 #if !NO_STOPWATCH
233 /// <summary>
234 /// Starts a new stopwatch object.
235 /// </summary>
236 /// <returns>New stopwatch object; started at the time of the request.</returns>
237 public override IStopwatch StartStopwatch()
238 {
239 //
240 // Strictly speaking, this explicit override is not necessary because the base implementation calls into
241 // the enlightenment module to obtain the CAL, which would circle back to System.Reactive.PlatformServices
242 // where we're currently running. This is merely a short-circuit to avoid the additional roundtrip.
243 //
244 return new StopwatchImpl();
245 }
246 #endif
247
248 /// <summary>
249 /// Ends the thread associated with this scheduler. All remaining work in the scheduler queue is abandoned.
250 /// </summary>
251 public void Dispose()
252 {
253 lock (_gate)
254 {
255 if (!_disposed)
256 {
257 _disposed = true;
258 _nextTimer.Dispose();
259 _evt.Release();
260 }
261 }
262 }
263
264 #endregion
265
266 #region Private implementation
267
268 /// <summary>
269 /// Ensures there is an event loop thread running. Should be called under the gate.
270 /// </summary>
271 private void EnsureThread()
272 {
273 if (_thread == null)
274 {
275 _thread = _threadFactory(Run);
276 _thread.Start();
277 }
278 }
279
280 /// <summary>
281 /// Event loop scheduled on the designated event loop thread. The loop is suspended/resumed using the event
282 /// which gets set by calls to Schedule, the next item timer, or calls to Dispose.
283 /// </summary>
284 private void Run()
285 {
286 while (true)
287 {
288 #if !NO_CDS
289 _evt.Wait();
290 #else
291 _evt.WaitOne();
292 #endif
293
294 var ready = default(ScheduledItem<TimeSpan>[]);
295
296 lock (_gate)
297 {
298 //
299 // Bug fix that ensures the number of calls to Release never greatly exceeds the number of calls to Wait.
300 // See work item #37: https://rx.codeplex.com/workitem/37
301 //
302 #if !NO_CDS
303 while (_evt.CurrentCount > 0) _evt.Wait();
304 #else
305 while (_evt.WaitOne(TimeSpan.Zero)) { }
306 #endif
307
308 //
309 // The event could have been set by a call to Dispose. This takes priority over anything else. We quit the
310 // loop immediately. Subsequent calls to Schedule won't ever create a new thread.
311 //
312 if (_disposed)
313 {
314 ((IDisposable)_evt).Dispose();
315 return;
316 }
317
318 while (_queue.Count > 0 && _queue.Peek().DueTime <= _stopwatch.Elapsed)
319 {
320 var item = _queue.Dequeue();
321 _readyList.Enqueue(item);
322 }
323
324 if (_queue.Count > 0)
325 {
326 var next = _queue.Peek();
327 if (next != _nextItem)
328 {
329 _nextItem = next;
330
331 var due = next.DueTime - _stopwatch.Elapsed;
332 _nextTimer.Disposable = ConcurrencyAbstractionLayer.Current.StartTimer(Tick, next, due);
333 }
334 }
335
336 if (_readyList.Count > 0)
337 {
338 ready = _readyList.ToArray();
339 _readyList.Clear();
340 }
341 }
342
343 if (ready != null)
344 {
345 foreach (var item in ready)
346 {
347 if (!item.IsCanceled)
348 item.Invoke();
349 }
350 }
351
352 if (ExitIfEmpty)
353 {
354 lock (_gate)
355 {
356 if (_readyList.Count == 0 && _queue.Count == 0)
357 {
358 _thread = null;
359 return;
360 }
361 }
362 }
363 }
364 }
365
366 private void Tick(object state)
367 {
368 lock (_gate)
369 {
370 if (!_disposed)
371 {
372 var item = (ScheduledItem<TimeSpan>)state;
373 if (_queue.Remove(item))
374 {
375 _readyList.Enqueue(item);
376 }
377
378 _evt.Release();
379 }
380 }
381 }
382
383 #endregion
384 }
385 }