forked from haoduotnt/aspnetwebstack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTaskHelpers.cs
299 lines (264 loc) · 12.7 KB
/
TaskHelpers.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Threading.Tasks
{
/// <summary>
/// Helpers for safely using Task libraries.
/// </summary>
internal static class TaskHelpers
{
private static readonly Task _defaultCompleted = FromResult<AsyncVoid>(default(AsyncVoid));
private static readonly Task<object> _completedTaskReturningNull = FromResult<object>(null);
/// <summary>
/// Returns a canceled Task. The task is completed, IsCanceled = True, IsFaulted = False.
/// </summary>
internal static Task Canceled()
{
return CancelCache<AsyncVoid>.Canceled;
}
/// <summary>
/// Returns a canceled Task of the given type. The task is completed, IsCanceled = True, IsFaulted = False.
/// </summary>
internal static Task<TResult> Canceled<TResult>()
{
return CancelCache<TResult>.Canceled;
}
/// <summary>
/// Returns a completed task that has no result.
/// </summary>
internal static Task Completed()
{
return _defaultCompleted;
}
/// <summary>
/// Returns an error task. The task is Completed, IsCanceled = False, IsFaulted = True
/// </summary>
internal static Task FromError(Exception exception)
{
return FromError<AsyncVoid>(exception);
}
/// <summary>
/// Returns an error task of the given type. The task is Completed, IsCanceled = False, IsFaulted = True
/// </summary>
/// <typeparam name="TResult"></typeparam>
internal static Task<TResult> FromError<TResult>(Exception exception)
{
TaskCompletionSource<TResult> tcs = new TaskCompletionSource<TResult>();
tcs.SetException(exception);
return tcs.Task;
}
/// <summary>
/// Returns an error task of the given type. The task is Completed, IsCanceled = False, IsFaulted = True
/// </summary>
internal static Task FromErrors(IEnumerable<Exception> exceptions)
{
return FromErrors<AsyncVoid>(exceptions);
}
/// <summary>
/// Returns an error task of the given type. The task is Completed, IsCanceled = False, IsFaulted = True
/// </summary>
internal static Task<TResult> FromErrors<TResult>(IEnumerable<Exception> exceptions)
{
TaskCompletionSource<TResult> tcs = new TaskCompletionSource<TResult>();
tcs.SetException(exceptions);
return tcs.Task;
}
/// <summary>
/// Returns a successful completed task with the given result.
/// </summary>
internal static Task<TResult> FromResult<TResult>(TResult result)
{
TaskCompletionSource<TResult> tcs = new TaskCompletionSource<TResult>();
tcs.SetResult(result);
return tcs.Task;
}
internal static Task<object> NullResult()
{
return _completedTaskReturningNull;
}
/// <summary>
/// Return a task that runs all the tasks inside the iterator sequentially. It stops as soon
/// as one of the tasks fails or cancels, or after all the tasks have run succesfully.
/// </summary>
/// <param name="asyncIterator">collection of tasks to wait on</param>
/// <param name="cancellationToken">cancellation token</param>
/// <param name="disposeEnumerator">whether or not to dispose the enumerator we get from <paramref name="asyncIterator"/>.
/// Only set to <c>false</c> if you can guarantee that <paramref name="asyncIterator"/>'s enumerator does not have any resources it needs to dispose.</param>
/// <returns>a task that signals completed when all the incoming tasks are finished.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is propagated in a Task.")]
internal static Task Iterate(IEnumerable<Task> asyncIterator, CancellationToken cancellationToken = default(CancellationToken), bool disposeEnumerator = true)
{
Contract.Assert(asyncIterator != null);
IEnumerator<Task> enumerator = null;
try
{
enumerator = asyncIterator.GetEnumerator();
Task task = IterateImpl(enumerator, cancellationToken);
return (disposeEnumerator && enumerator != null) ? task.Finally(enumerator.Dispose, runSynchronously: true) : task;
}
catch (Exception ex)
{
return TaskHelpers.FromError(ex);
}
}
/// <summary>
/// Provides the implementation of the Iterate method.
/// Contains special logic to help speed up common cases.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is propagated in a Task.")]
internal static Task IterateImpl(IEnumerator<Task> enumerator, CancellationToken cancellationToken)
{
try
{
while (true)
{
// short-circuit: iteration canceled
if (cancellationToken.IsCancellationRequested)
{
return TaskHelpers.Canceled();
}
// short-circuit: iteration complete
if (!enumerator.MoveNext())
{
return TaskHelpers.Completed();
}
// fast case: Task completed synchronously & successfully
Task currentTask = enumerator.Current;
if (currentTask.Status == TaskStatus.RanToCompletion)
{
continue;
}
// fast case: Task completed synchronously & unsuccessfully
if (currentTask.IsCanceled || currentTask.IsFaulted)
{
return currentTask;
}
// slow case: Task isn't yet complete
return IterateImplIncompleteTask(enumerator, currentTask, cancellationToken);
}
}
catch (Exception ex)
{
return TaskHelpers.FromError(ex);
}
}
/// <summary>
/// Fallback for IterateImpl when the antecedent Task isn't yet complete.
/// </summary>
internal static Task IterateImplIncompleteTask(IEnumerator<Task> enumerator, Task currentTask, CancellationToken cancellationToken)
{
// There's a race condition here, the antecedent Task could complete between
// the check in Iterate and the call to Then below. If this happens, we could
// end up growing the stack indefinitely. But the chances of (a) even having
// enough Tasks in the enumerator in the first place and of (b) *every* one
// of them hitting this race condition are so extremely remote that it's not
// worth worrying about.
return currentTask.Then(() => IterateImpl(enumerator, cancellationToken));
}
/// <summary>
/// Update the completion source if the task failed (cancelled or faulted). No change to completion source if the task succeeded.
/// </summary>
/// <typeparam name="TResult">result type of completion source</typeparam>
/// <param name="tcs">completion source to update</param>
/// <param name="source">task to update from.</param>
/// <returns>true on success</returns>
internal static bool SetIfTaskFailed<TResult>(this TaskCompletionSource<TResult> tcs, Task source)
{
switch (source.Status)
{
case TaskStatus.Canceled:
case TaskStatus.Faulted:
return tcs.TrySetFromTask(source);
}
return false;
}
/// <summary>
/// Set a completion source from the given Task.
/// </summary>
/// <typeparam name="TResult">result type for completion source.</typeparam>
/// <param name="tcs">completion source to set</param>
/// <param name="source">Task to get values from.</param>
/// <returns>true if this successfully sets the completion source.</returns>
[SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "This is a known safe usage of Task.Result, since it only occurs when we know the task's state to be completed.")]
internal static bool TrySetFromTask<TResult>(this TaskCompletionSource<TResult> tcs, Task source)
{
if (source.Status == TaskStatus.Canceled)
{
return tcs.TrySetCanceled();
}
if (source.Status == TaskStatus.Faulted)
{
return tcs.TrySetException(source.Exception.InnerExceptions);
}
if (source.Status == TaskStatus.RanToCompletion)
{
Task<TResult> taskOfResult = source as Task<TResult>;
return tcs.TrySetResult(taskOfResult == null ? default(TResult) : taskOfResult.Result);
}
return false;
}
/// <summary>
/// Set a completion source from the given Task. If the task ran to completion and the result type doesn't match
/// the type of the completion source, then a default value will be used. This is useful for converting Task into
/// Task{AsyncVoid}, but it can also accidentally be used to introduce data loss (by passing the wrong
/// task type), so please execute this method with care.
/// </summary>
/// <typeparam name="TResult">result type for completion source.</typeparam>
/// <param name="tcs">completion source to set</param>
/// <param name="source">Task to get values from.</param>
/// <returns>true if this successfully sets the completion source.</returns>
[SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "This is a known safe usage of Task.Result, since it only occurs when we know the task's state to be completed.")]
internal static bool TrySetFromTask<TResult>(this TaskCompletionSource<Task<TResult>> tcs, Task source)
{
if (source.Status == TaskStatus.Canceled)
{
return tcs.TrySetCanceled();
}
if (source.Status == TaskStatus.Faulted)
{
return tcs.TrySetException(source.Exception.InnerExceptions);
}
if (source.Status == TaskStatus.RanToCompletion)
{
// Sometimes the source task is Task<Task<TResult>>, and sometimes it's Task<TResult>.
// The latter usually happens when we're in the middle of a sync-block postback where
// the continuation is a function which returns Task<TResult> rather than just TResult,
// but the originating task was itself just Task<TResult>. An example of this can be
// found in TaskExtensions.CatchImpl().
Task<Task<TResult>> taskOfTaskOfResult = source as Task<Task<TResult>>;
if (taskOfTaskOfResult != null)
{
return tcs.TrySetResult(taskOfTaskOfResult.Result);
}
Task<TResult> taskOfResult = source as Task<TResult>;
if (taskOfResult != null)
{
return tcs.TrySetResult(taskOfResult);
}
return tcs.TrySetResult(TaskHelpers.FromResult(default(TResult)));
}
return false;
}
/// <summary>
/// Used as the T in a "conversion" of a Task into a Task{T}
/// </summary>
private struct AsyncVoid
{
}
/// <summary>
/// This class is a convenient cache for per-type cancelled tasks
/// </summary>
private static class CancelCache<TResult>
{
public static readonly Task<TResult> Canceled = GetCancelledTask();
private static Task<TResult> GetCancelledTask()
{
TaskCompletionSource<TResult> tcs = new TaskCompletionSource<TResult>();
tcs.SetCanceled();
return tcs.Task;
}
}
}
}