Debian Codegraph @

external/rx/Rx/NET/Source/System.Reactive.PlatformServices/Reactive/Concurrency/TaskPoolScheduler.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_TPL
4 using System.Reactive.Disposables;
5 using System.Threading;
6 using System.Threading.Tasks;
7
8 namespace System.Reactive.Concurrency
9 {
10 /// <summary>
11 /// Represents an object that schedules units of work on the Task Parallel Library (TPL) task pool.
12 /// </summary>
13 /// <seealso cref="TaskPoolScheduler.Default">Instance of this type using the default TaskScheduler to schedule work on the TPL task pool.</seealso>
14 public sealed class TaskPoolScheduler : LocalScheduler, ISchedulerLongRunning, ISchedulerPeriodic
15 {
16 private static readonly TaskPoolScheduler s_instance = new TaskPoolScheduler(new TaskFactory(TaskScheduler.Default));
17 private readonly TaskFactory taskFactory;
18
19 /// <summary>
20 /// Creates an object that schedules units of work using the provided TaskFactory.
21 /// </summary>
22 /// <param name="taskFactory">Task factory used to create tasks to run units of work.</param>
23 /// <exception cref="ArgumentNullException"><paramref name="taskFactory"/> is null.</exception>
24 public TaskPoolScheduler(TaskFactory taskFactory)
25 {
26 if (taskFactory == null)
27 throw new ArgumentNullException("taskFactory");
28
29 this.taskFactory = taskFactory;
30 }
31
32 /// <summary>
33 /// Gets an instance of this scheduler that uses the default TaskScheduler.
34 /// </summary>
35 public static TaskPoolScheduler Default
36 {
37 get
38 {
39 return s_instance;
40 }
41 }
42
43 /// <summary>
44 /// Schedules an action to be executed.
45 /// </summary>
46 /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
47 /// <param name="state">State passed to the action to be executed.</param>
48 /// <param name="action">Action to be executed.</param>
49 /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
50 /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
51 public override IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
52 {
53 if (action == null)
54 throw new ArgumentNullException("action");
55
56 var d = new SerialDisposable();
57 var cancelable = new CancellationDisposable();
58 d.Disposable = cancelable;
59 taskFactory.StartNew(() =>
60 {
61 //
62 // BREAKING CHANGE v2.0 > v1.x - No longer escalating exceptions using a throwing
63 // helper thread.
64 //
65 // Our manual escalation based on the creation of a throwing thread was merely to
66 // expedite the process of throwing the exception that would otherwise occur on the
67 // finalizer thread at a later point during the app's lifetime.
68 //
69 // However, it also prevented applications from observing the exception through
70 // the TaskScheduler.UnobservedTaskException static event. Also, starting form .NET
71 // 4.5, the default behavior of the task pool is not to take down the application
72 // when an exception goes unobserved (done as part of the async/await work). It'd
73 // be weird for Rx not to follow the platform defaults.
74 //
75 // General implementation guidelines for schedulers (in order of importance):
76 //
77 // 1. Always thunk through to the underlying infrastructure with a wrapper that's as tiny as possible.
78 // 2. Global exception notification/handling mechanisms shouldn't be bypassed.
79 // 3. Escalation behavior for exceptions is left to the underlying infrastructure.
80 //
81 // The Catch extension method for IScheduler (added earlier) allows to re-route
82 // exceptions at stage 2. If the exception isn't handled at the Rx level, it
83 // propagates by means of a rethrow, falling back to behavior in 3.
84 //
85 d.Disposable = action(this, state);
86 }, cancelable.Token);
87 return d;
88 }
89
90 /// <summary>
91 /// Schedules an action to be executed after dueTime.
92 /// </summary>
93 /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
94 /// <param name="state">State passed to the action to be executed.</param>
95 /// <param name="action">Action to be executed.</param>
96 /// <param name="dueTime">Relative time after which to execute the action.</param>
97 /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
98 /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
99 public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
100 {
101 if (action == null)
102 throw new ArgumentNullException("action");
103
104 var dt = Scheduler.Normalize(dueTime);
105 if (dt.Ticks == 0)
106 return Schedule(state, action);
107
108 #if !NO_TASK_DELAY
109 var d = new MultipleAssignmentDisposable();
110
111 var ct = new CancellationDisposable();
112 d.Disposable = ct;
113
114 #if USE_TASKEX
115 TaskEx.Delay(dueTime, ct.Token).ContinueWith(_ =>
116 #else
117 Task.Delay(dueTime, ct.Token).ContinueWith(_ =>
118 #endif
119 {
120 if (!d.IsDisposed)
121 d.Disposable = action(this, state);
122 }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion, taskFactory.Scheduler);
123
124 return d;
125 #else
126 return DefaultScheduler.Instance.Schedule(state, dt, (_, state1) => Schedule(state1, action));
127 #endif
128 }
129
130 /// <summary>
131 /// Schedules a long-running task by creating a new task using TaskCreationOptions.LongRunning. Cancellation happens through polling.
132 /// </summary>
133 /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
134 /// <param name="state">State passed to the action to be executed.</param>
135 /// <param name="action">Action to be executed.</param>
136 /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
137 /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
138 public IDisposable ScheduleLongRunning<TState>(TState state, Action<TState, ICancelable> action)
139 {
140 var d = new BooleanDisposable();
141
142 taskFactory.StartNew(() =>
143 {
144 //
145 // Notice we don't check d.IsDisposed. The contract for ISchedulerLongRunning
146 // requires us to ensure the scheduled work gets an opportunity to observe
147 // the cancellation request.
148 //
149 action(state, d);
150 }, TaskCreationOptions.LongRunning);
151
152 return d;
153 }
154
155 #if !NO_STOPWATCH
156 /// <summary>
157 /// Gets a new stopwatch ob ject.
158 /// </summary>
159 /// <returns>New stopwatch object; started at the time of the request.</returns>
160 public override IStopwatch StartStopwatch()
161 {
162 //
163 // Strictly speaking, this explicit override is not necessary because the base implementation calls into
164 // the enlightenment module to obtain the CAL, which would circle back to System.Reactive.PlatformServices
165 // where we're currently running. This is merely a short-circuit to avoid the additional roundtrip.
166 //
167 return new StopwatchImpl();
168 }
169 #endif
170
171 /// <summary>
172 /// Schedules a periodic piece of work by running a platform-specific timer to create tasks periodically.
173 /// </summary>
174 /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
175 /// <param name="state">Initial state passed to the action upon the first iteration.</param>
176 /// <param name="period">Period for running the work periodically.</param>
177 /// <param name="action">Action to be executed, potentially updating the state.</param>
178 /// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns>
179 /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
180 /// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than TimeSpan.Zero.</exception>
181 public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action)
182 {
183 if (period < TimeSpan.Zero)
184 throw new ArgumentOutOfRangeException("period");
185 if (action == null)
186 throw new ArgumentNullException("action");
187
188 #if !NO_TASK_DELAY
189 var cancel = new CancellationDisposable();
190
191 var state1 = state;
192 var gate = new AsyncLock();
193
194 var moveNext = default(Action);
195 moveNext = () =>
196 {
197 #if USE_TASKEX
198 TaskEx.Delay(period, cancel.Token).ContinueWith(
199 #else
200 Task.Delay(period, cancel.Token).ContinueWith(
201 #endif
202 _ =>
203 {
204 moveNext();
205
206 gate.Wait(() =>
207 {
208 state1 = action(state1);
209 });
210 },
211 CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion, taskFactory.Scheduler
212 );
213 };
214
215 moveNext();
216
217 return new CompositeDisposable(cancel, gate);
218 #else
219 var state1 = state;
220 var gate = new AsyncLock();
221
222 var timer = ConcurrencyAbstractionLayer.Current.StartPeriodicTimer(() =>
223 {
224 taskFactory.StartNew(() =>
225 {
226 gate.Wait(() =>
227 {
228 state1 = action(state1);
229 });
230 });
231 }, period);
232
233 return new CompositeDisposable(timer, gate);
234 #endif
235 }
236 }
237 }
238 #endif