mscorlib(4.0.0.0) API with additions
Task.cs
3 using System.Diagnostics;
7 using System.Security;
9 
10 namespace System.Threading.Tasks
11 {
14  [DebuggerTypeProxy(typeof(SystemThreadingTasks_FutureDebugView<>))]
15  [DebuggerDisplay("Id = {Id}, Status = {Status}, Method = {DebuggerDisplayMethodDescription}, Result = {DebuggerDisplayResultDescription}")]
16  [__DynamicallyInvokable]
17  [HostProtection(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
18  public class Task<TResult> : Task
19  {
20  internal TResult m_result;
21 
22  private static readonly TaskFactory<TResult> s_Factory = new TaskFactory<TResult>();
23 
24  internal static readonly Func<Task<Task>, Task<TResult>> TaskWhenAnyCast = (Task<Task> completed) => (Task<TResult>)completed.Result;
25 
26  private string DebuggerDisplayResultDescription
27  {
28  get
29  {
30  if (!base.IsRanToCompletion)
31  {
32  return Environment.GetResourceString("TaskT_DebuggerNoResult");
33  }
34  return string.Concat(m_result);
35  }
36  }
37 
38  private string DebuggerDisplayMethodDescription
39  {
40  get
41  {
42  Delegate @delegate = (Delegate)m_action;
43  if ((object)@delegate == null)
44  {
45  return "{null}";
46  }
47  return @delegate.Method.ToString();
48  }
49  }
50 
54  [DebuggerBrowsable(DebuggerBrowsableState.Never)]
55  [__DynamicallyInvokable]
56  public TResult Result
57  {
58  [__DynamicallyInvokable]
59  get
60  {
61  if (!base.IsWaitNotificationEnabledOrNotRanToCompletion)
62  {
63  return m_result;
64  }
65  return GetResultCore(waitCompletionNotification: true);
66  }
67  }
68 
69  internal TResult ResultOnSuccess => m_result;
70 
73  [__DynamicallyInvokable]
74  public new static TaskFactory<TResult> Factory
75  {
76  [__DynamicallyInvokable]
77  get
78  {
79  return s_Factory;
80  }
81  }
82 
83  internal Task()
84  {
85  }
86 
87  internal Task(object state, TaskCreationOptions options)
88  : base(state, options, promiseStyle: true)
89  {
90  }
91 
92  internal Task(TResult result)
93  : base(canceled: false, TaskCreationOptions.None, default(CancellationToken))
94  {
95  m_result = result;
96  }
97 
98  internal Task(bool canceled, TResult result, TaskCreationOptions creationOptions, CancellationToken ct)
99  : base(canceled, creationOptions, ct)
100  {
101  if (!canceled)
102  {
103  m_result = result;
104  }
105  }
106 
110  [MethodImpl(MethodImplOptions.NoInlining)]
111  [__DynamicallyInvokable]
112  public Task(Func<TResult> function)
113  : this(function, (Task)null, default(CancellationToken), TaskCreationOptions.None, InternalTaskOptions.None, (TaskScheduler)null)
114  {
115  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
116  PossiblyCaptureContext(ref stackMark);
117  }
118 
124  [MethodImpl(MethodImplOptions.NoInlining)]
125  [__DynamicallyInvokable]
126  public Task(Func<TResult> function, CancellationToken cancellationToken)
127  : this(function, (Task)null, cancellationToken, TaskCreationOptions.None, InternalTaskOptions.None, (TaskScheduler)null)
128  {
129  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
130  PossiblyCaptureContext(ref stackMark);
131  }
132 
138  [MethodImpl(MethodImplOptions.NoInlining)]
139  [__DynamicallyInvokable]
140  public Task(Func<TResult> function, TaskCreationOptions creationOptions)
141  : this(function, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, InternalTaskOptions.None, (TaskScheduler)null)
142  {
143  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
144  PossiblyCaptureContext(ref stackMark);
145  }
146 
154  [MethodImpl(MethodImplOptions.NoInlining)]
155  [__DynamicallyInvokable]
156  public Task(Func<TResult> function, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
157  : this(function, Task.InternalCurrentIfAttached(creationOptions), cancellationToken, creationOptions, InternalTaskOptions.None, (TaskScheduler)null)
158  {
159  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
160  PossiblyCaptureContext(ref stackMark);
161  }
162 
167  [MethodImpl(MethodImplOptions.NoInlining)]
168  [__DynamicallyInvokable]
169  public Task(Func<object, TResult> function, object state)
170  : this((Delegate)function, state, (Task)null, default(CancellationToken), TaskCreationOptions.None, InternalTaskOptions.None, (TaskScheduler)null)
171  {
172  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
173  PossiblyCaptureContext(ref stackMark);
174  }
175 
182  [MethodImpl(MethodImplOptions.NoInlining)]
183  [__DynamicallyInvokable]
184  public Task(Func<object, TResult> function, object state, CancellationToken cancellationToken)
185  : this((Delegate)function, state, (Task)null, cancellationToken, TaskCreationOptions.None, InternalTaskOptions.None, (TaskScheduler)null)
186  {
187  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
188  PossiblyCaptureContext(ref stackMark);
189  }
190 
197  [MethodImpl(MethodImplOptions.NoInlining)]
198  [__DynamicallyInvokable]
199  public Task(Func<object, TResult> function, object state, TaskCreationOptions creationOptions)
200  : this((Delegate)function, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, InternalTaskOptions.None, (TaskScheduler)null)
201  {
202  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
203  PossiblyCaptureContext(ref stackMark);
204  }
205 
214  [MethodImpl(MethodImplOptions.NoInlining)]
215  [__DynamicallyInvokable]
216  public Task(Func<object, TResult> function, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
217  : this((Delegate)function, state, Task.InternalCurrentIfAttached(creationOptions), cancellationToken, creationOptions, InternalTaskOptions.None, (TaskScheduler)null)
218  {
219  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
220  PossiblyCaptureContext(ref stackMark);
221  }
222 
223  internal Task(Func<TResult> valueSelector, Task parent, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler, ref StackCrawlMark stackMark)
224  : this(valueSelector, parent, cancellationToken, creationOptions, internalOptions, scheduler)
225  {
226  PossiblyCaptureContext(ref stackMark);
227  }
228 
229  internal Task(Func<TResult> valueSelector, Task parent, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler)
230  : base(valueSelector, null, parent, cancellationToken, creationOptions, internalOptions, scheduler)
231  {
232  if ((internalOptions & InternalTaskOptions.SelfReplicating) != 0)
233  {
234  throw new ArgumentOutOfRangeException("creationOptions", Environment.GetResourceString("TaskT_ctor_SelfReplicating"));
235  }
236  }
237 
238  internal Task(Func<object, TResult> valueSelector, object state, Task parent, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler, ref StackCrawlMark stackMark)
239  : this((Delegate)valueSelector, state, parent, cancellationToken, creationOptions, internalOptions, scheduler)
240  {
241  PossiblyCaptureContext(ref stackMark);
242  }
243 
244  internal Task(Delegate valueSelector, object state, Task parent, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler)
245  : base(valueSelector, state, parent, cancellationToken, creationOptions, internalOptions, scheduler)
246  {
247  if ((internalOptions & InternalTaskOptions.SelfReplicating) != 0)
248  {
249  throw new ArgumentOutOfRangeException("creationOptions", Environment.GetResourceString("TaskT_ctor_SelfReplicating"));
250  }
251  }
252 
253  internal static Task<TResult> StartNew(Task parent, Func<TResult> function, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler, ref StackCrawlMark stackMark)
254  {
255  if (function == null)
256  {
257  throw new ArgumentNullException("function");
258  }
259  if (scheduler == null)
260  {
261  throw new ArgumentNullException("scheduler");
262  }
263  if ((internalOptions & InternalTaskOptions.SelfReplicating) != 0)
264  {
265  throw new ArgumentOutOfRangeException("creationOptions", Environment.GetResourceString("TaskT_ctor_SelfReplicating"));
266  }
267  Task<TResult> task = new Task<TResult>(function, parent, cancellationToken, creationOptions, internalOptions | InternalTaskOptions.QueuedByRuntime, scheduler, ref stackMark);
268  task.ScheduleAndStart(needsProtection: false);
269  return task;
270  }
271 
272  internal static Task<TResult> StartNew(Task parent, Func<object, TResult> function, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler, ref StackCrawlMark stackMark)
273  {
274  if (function == null)
275  {
276  throw new ArgumentNullException("function");
277  }
278  if (scheduler == null)
279  {
280  throw new ArgumentNullException("scheduler");
281  }
282  if ((internalOptions & InternalTaskOptions.SelfReplicating) != 0)
283  {
284  throw new ArgumentOutOfRangeException("creationOptions", Environment.GetResourceString("TaskT_ctor_SelfReplicating"));
285  }
286  Task<TResult> task = new Task<TResult>(function, state, parent, cancellationToken, creationOptions, internalOptions | InternalTaskOptions.QueuedByRuntime, scheduler, ref stackMark);
287  task.ScheduleAndStart(needsProtection: false);
288  return task;
289  }
290 
291  internal bool TrySetResult(TResult result)
292  {
293  if (base.IsCompleted)
294  {
295  return false;
296  }
297  if (AtomicStateUpdate(67108864, 90177536))
298  {
299  m_result = result;
300  Interlocked.Exchange(ref m_stateFlags, m_stateFlags | 0x1000000);
301  m_contingentProperties?.SetCompleted();
302  FinishStageThree();
303  return true;
304  }
305  return false;
306  }
307 
308  internal void DangerousSetResult(TResult result)
309  {
310  if (m_parent != null)
311  {
312  bool flag = TrySetResult(result);
313  return;
314  }
315  m_result = result;
316  m_stateFlags |= 16777216;
317  }
318 
319  internal TResult GetResultCore(bool waitCompletionNotification)
320  {
321  if (!base.IsCompleted)
322  {
323  InternalWait(-1, default(CancellationToken));
324  }
325  if (waitCompletionNotification)
326  {
327  NotifyDebuggerOfWaitCompletionIfNecessary();
328  }
329  if (!base.IsRanToCompletion)
330  {
331  ThrowIfExceptional(includeTaskCanceledExceptions: true);
332  }
333  return m_result;
334  }
335 
336  internal bool TrySetException(object exceptionObject)
337  {
338  bool result = false;
339  EnsureContingentPropertiesInitialized(needsProtection: true);
340  if (AtomicStateUpdate(67108864, 90177536))
341  {
342  AddException(exceptionObject);
343  Finish(bUserDelegateExecuted: false);
344  result = true;
345  }
346  return result;
347  }
348 
349  internal bool TrySetCanceled(CancellationToken tokenToRecord)
350  {
351  return TrySetCanceled(tokenToRecord, null);
352  }
353 
354  internal bool TrySetCanceled(CancellationToken tokenToRecord, object cancellationException)
355  {
356  bool result = false;
357  if (AtomicStateUpdate(67108864, 90177536))
358  {
359  RecordInternalCancellationRequest(tokenToRecord, cancellationException);
360  CancellationCleanupLogic();
361  result = true;
362  }
363  return result;
364  }
365 
366  internal override void InnerInvoke()
367  {
368  Func<TResult> func = m_action as Func<TResult>;
369  if (func != null)
370  {
371  m_result = func();
372  return;
373  }
374  Func<object, TResult> func2 = m_action as Func<object, TResult>;
375  if (func2 != null)
376  {
377  m_result = func2(m_stateObject);
378  }
379  }
380 
383  [__DynamicallyInvokable]
385  {
386  return new TaskAwaiter<TResult>(this);
387  }
388 
392  [__DynamicallyInvokable]
393  public new ConfiguredTaskAwaitable<TResult> ConfigureAwait(bool continueOnCapturedContext)
394  {
395  return new ConfiguredTaskAwaitable<TResult>(this, continueOnCapturedContext);
396  }
397 
403  [MethodImpl(MethodImplOptions.NoInlining)]
404  [__DynamicallyInvokable]
405  public Task ContinueWith(Action<Task<TResult>> continuationAction)
406  {
407  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
408  return ContinueWith(continuationAction, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
409  }
410 
417  [MethodImpl(MethodImplOptions.NoInlining)]
418  [__DynamicallyInvokable]
419  public Task ContinueWith(Action<Task<TResult>> continuationAction, CancellationToken cancellationToken)
420  {
421  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
422  return ContinueWith(continuationAction, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None, ref stackMark);
423  }
424 
431  [MethodImpl(MethodImplOptions.NoInlining)]
432  [__DynamicallyInvokable]
433  public Task ContinueWith(Action<Task<TResult>> continuationAction, TaskScheduler scheduler)
434  {
435  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
436  return ContinueWith(continuationAction, scheduler, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
437  }
438 
446  [MethodImpl(MethodImplOptions.NoInlining)]
447  [__DynamicallyInvokable]
448  public Task ContinueWith(Action<Task<TResult>> continuationAction, TaskContinuationOptions continuationOptions)
449  {
450  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
451  return ContinueWith(continuationAction, TaskScheduler.Current, default(CancellationToken), continuationOptions, ref stackMark);
452  }
453 
463  [MethodImpl(MethodImplOptions.NoInlining)]
464  [__DynamicallyInvokable]
465  public Task ContinueWith(Action<Task<TResult>> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
466  {
467  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
468  return ContinueWith(continuationAction, scheduler, cancellationToken, continuationOptions, ref stackMark);
469  }
470 
471  internal Task ContinueWith(Action<Task<TResult>> continuationAction, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, ref StackCrawlMark stackMark)
472  {
473  if (continuationAction == null)
474  {
475  throw new ArgumentNullException("continuationAction");
476  }
477  if (scheduler == null)
478  {
479  throw new ArgumentNullException("scheduler");
480  }
481  Task.CreationOptionsFromContinuationOptions(continuationOptions, out TaskCreationOptions creationOptions, out InternalTaskOptions internalOptions);
482  Task task = new ContinuationTaskFromResultTask<TResult>(this, continuationAction, null, creationOptions, internalOptions, ref stackMark);
483  ContinueWithCore(task, scheduler, cancellationToken, continuationOptions);
484  return task;
485  }
486 
492  [MethodImpl(MethodImplOptions.NoInlining)]
493  [__DynamicallyInvokable]
494  public Task ContinueWith(Action<Task<TResult>, object> continuationAction, object state)
495  {
496  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
497  return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
498  }
499 
507  [MethodImpl(MethodImplOptions.NoInlining)]
508  [__DynamicallyInvokable]
509  public Task ContinueWith(Action<Task<TResult>, object> continuationAction, object state, CancellationToken cancellationToken)
510  {
511  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
512  return ContinueWith(continuationAction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None, ref stackMark);
513  }
514 
522  [MethodImpl(MethodImplOptions.NoInlining)]
523  [__DynamicallyInvokable]
524  public Task ContinueWith(Action<Task<TResult>, object> continuationAction, object state, TaskScheduler scheduler)
525  {
526  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
527  return ContinueWith(continuationAction, state, scheduler, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
528  }
529 
537  [MethodImpl(MethodImplOptions.NoInlining)]
538  [__DynamicallyInvokable]
539  public Task ContinueWith(Action<Task<TResult>, object> continuationAction, object state, TaskContinuationOptions continuationOptions)
540  {
541  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
542  return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions, ref stackMark);
543  }
544 
556  [MethodImpl(MethodImplOptions.NoInlining)]
557  [__DynamicallyInvokable]
558  public Task ContinueWith(Action<Task<TResult>, object> continuationAction, object state, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
559  {
560  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
561  return ContinueWith(continuationAction, state, scheduler, cancellationToken, continuationOptions, ref stackMark);
562  }
563 
564  internal Task ContinueWith(Action<Task<TResult>, object> continuationAction, object state, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, ref StackCrawlMark stackMark)
565  {
566  if (continuationAction == null)
567  {
568  throw new ArgumentNullException("continuationAction");
569  }
570  if (scheduler == null)
571  {
572  throw new ArgumentNullException("scheduler");
573  }
574  Task.CreationOptionsFromContinuationOptions(continuationOptions, out TaskCreationOptions creationOptions, out InternalTaskOptions internalOptions);
575  Task task = new ContinuationTaskFromResultTask<TResult>(this, continuationAction, state, creationOptions, internalOptions, ref stackMark);
576  ContinueWithCore(task, scheduler, cancellationToken, continuationOptions);
577  return task;
578  }
579 
586  [MethodImpl(MethodImplOptions.NoInlining)]
587  [__DynamicallyInvokable]
588  public Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, TNewResult> continuationFunction)
589  {
590  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
591  return ContinueWith(continuationFunction, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
592  }
593 
601  [MethodImpl(MethodImplOptions.NoInlining)]
602  [__DynamicallyInvokable]
603  public Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, TNewResult> continuationFunction, CancellationToken cancellationToken)
604  {
605  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
606  return ContinueWith(continuationFunction, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None, ref stackMark);
607  }
608 
616  [MethodImpl(MethodImplOptions.NoInlining)]
617  [__DynamicallyInvokable]
618  public Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, TNewResult> continuationFunction, TaskScheduler scheduler)
619  {
620  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
621  return ContinueWith(continuationFunction, scheduler, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
622  }
623 
632  [MethodImpl(MethodImplOptions.NoInlining)]
633  [__DynamicallyInvokable]
634  public Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, TNewResult> continuationFunction, TaskContinuationOptions continuationOptions)
635  {
636  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
637  return ContinueWith(continuationFunction, TaskScheduler.Current, default(CancellationToken), continuationOptions, ref stackMark);
638  }
639 
650  [MethodImpl(MethodImplOptions.NoInlining)]
651  [__DynamicallyInvokable]
652  public Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, TNewResult> continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
653  {
654  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
655  return ContinueWith(continuationFunction, scheduler, cancellationToken, continuationOptions, ref stackMark);
656  }
657 
658  internal Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, TNewResult> continuationFunction, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, ref StackCrawlMark stackMark)
659  {
660  if (continuationFunction == null)
661  {
662  throw new ArgumentNullException("continuationFunction");
663  }
664  if (scheduler == null)
665  {
666  throw new ArgumentNullException("scheduler");
667  }
668  Task.CreationOptionsFromContinuationOptions(continuationOptions, out TaskCreationOptions creationOptions, out InternalTaskOptions internalOptions);
669  Task<TNewResult> task = new ContinuationResultTaskFromResultTask<TResult, TNewResult>(this, continuationFunction, null, creationOptions, internalOptions, ref stackMark);
670  ContinueWithCore(task, scheduler, cancellationToken, continuationOptions);
671  return task;
672  }
673 
680  [MethodImpl(MethodImplOptions.NoInlining)]
681  [__DynamicallyInvokable]
682  public Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, object, TNewResult> continuationFunction, object state)
683  {
684  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
685  return ContinueWith(continuationFunction, state, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
686  }
687 
696  [MethodImpl(MethodImplOptions.NoInlining)]
697  [__DynamicallyInvokable]
698  public Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, object, TNewResult> continuationFunction, object state, CancellationToken cancellationToken)
699  {
700  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
701  return ContinueWith(continuationFunction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None, ref stackMark);
702  }
703 
712  [MethodImpl(MethodImplOptions.NoInlining)]
713  [__DynamicallyInvokable]
714  public Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, object, TNewResult> continuationFunction, object state, TaskScheduler scheduler)
715  {
716  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
717  return ContinueWith(continuationFunction, state, scheduler, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
718  }
719 
728  [MethodImpl(MethodImplOptions.NoInlining)]
729  [__DynamicallyInvokable]
730  public Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, object, TNewResult> continuationFunction, object state, TaskContinuationOptions continuationOptions)
731  {
732  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
733  return ContinueWith(continuationFunction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions, ref stackMark);
734  }
735 
748  [MethodImpl(MethodImplOptions.NoInlining)]
749  [__DynamicallyInvokable]
750  public Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, object, TNewResult> continuationFunction, object state, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
751  {
752  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
753  return ContinueWith(continuationFunction, state, scheduler, cancellationToken, continuationOptions, ref stackMark);
754  }
755 
756  internal Task<TNewResult> ContinueWith<TNewResult>(Func<Task<TResult>, object, TNewResult> continuationFunction, object state, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, ref StackCrawlMark stackMark)
757  {
758  if (continuationFunction == null)
759  {
760  throw new ArgumentNullException("continuationFunction");
761  }
762  if (scheduler == null)
763  {
764  throw new ArgumentNullException("scheduler");
765  }
766  Task.CreationOptionsFromContinuationOptions(continuationOptions, out TaskCreationOptions creationOptions, out InternalTaskOptions internalOptions);
767  Task<TNewResult> task = new ContinuationResultTaskFromResultTask<TResult, TNewResult>(this, continuationFunction, state, creationOptions, internalOptions, ref stackMark);
768  ContinueWithCore(task, scheduler, cancellationToken, continuationOptions);
769  return task;
770  }
771  }
773  [DebuggerTypeProxy(typeof(SystemThreadingTasks_TaskDebugView))]
774  [DebuggerDisplay("Id = {Id}, Status = {Status}, Method = {DebuggerDisplayMethodDescription}")]
775  [__DynamicallyInvokable]
776  [HostProtection(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
777  public class Task : IThreadPoolWorkItem, IAsyncResult, IDisposable
778  {
779  internal class ContingentProperties
780  {
781  internal ExecutionContext m_capturedContext;
782 
783  internal volatile ManualResetEventSlim m_completionEvent;
784 
785  internal volatile TaskExceptionHolder m_exceptionsHolder;
786 
787  internal CancellationToken m_cancellationToken;
788 
789  internal Shared<CancellationTokenRegistration> m_cancellationRegistration;
790 
791  internal volatile int m_internalCancellationRequested;
792 
793  internal volatile int m_completionCountdown = 1;
794 
795  internal volatile List<Task> m_exceptionalChildren;
796 
797  internal void SetCompleted()
798  {
799  m_completionEvent?.Set();
800  }
801 
802  internal void DeregisterCancellationCallback()
803  {
804  if (m_cancellationRegistration != null)
805  {
806  try
807  {
808  m_cancellationRegistration.Value.Dispose();
809  }
810  catch (ObjectDisposedException)
811  {
812  }
813  m_cancellationRegistration = null;
814  }
815  }
816  }
817 
818  private sealed class SetOnInvokeMres : ManualResetEventSlim, ITaskCompletionAction
819  {
820  internal SetOnInvokeMres()
821  : base(initialState: false, 0)
822  {
823  }
824 
825  public void Invoke(Task completingTask)
826  {
827  Set();
828  }
829  }
830 
831  private sealed class SetOnCountdownMres : ManualResetEventSlim, ITaskCompletionAction
832  {
833  private int _count;
834 
835  internal SetOnCountdownMres(int count)
836  {
837  _count = count;
838  }
839 
840  public void Invoke(Task completingTask)
841  {
842  if (Interlocked.Decrement(ref _count) == 0)
843  {
844  Set();
845  }
846  }
847  }
848 
849  private sealed class DelayPromise : Task<VoidTaskResult>
850  {
851  internal readonly CancellationToken Token;
852 
853  internal CancellationTokenRegistration Registration;
854 
855  internal Timer Timer;
856 
857  internal DelayPromise(CancellationToken token)
858  {
859  Token = token;
860  if (AsyncCausalityTracer.LoggingOn)
861  {
862  AsyncCausalityTracer.TraceOperationCreation(CausalityTraceLevel.Required, base.Id, "Task.Delay", 0uL);
863  }
864  if (s_asyncDebuggingEnabled)
865  {
866  AddToActiveTasks(this);
867  }
868  }
869 
870  internal void Complete()
871  {
872  bool flag;
873  if (Token.IsCancellationRequested)
874  {
875  flag = TrySetCanceled(Token);
876  }
877  else
878  {
879  if (AsyncCausalityTracer.LoggingOn)
880  {
881  AsyncCausalityTracer.TraceOperationCompletion(CausalityTraceLevel.Required, base.Id, AsyncCausalityStatus.Completed);
882  }
883  if (s_asyncDebuggingEnabled)
884  {
885  RemoveFromActiveTasks(base.Id);
886  }
887  flag = TrySetResult(default(VoidTaskResult));
888  }
889  if (flag)
890  {
891  if (Timer != null)
892  {
893  Timer.Dispose();
894  }
895  Registration.Dispose();
896  }
897  }
898  }
899 
900  private sealed class WhenAllPromise : Task<VoidTaskResult>, ITaskCompletionAction
901  {
902  private readonly Task[] m_tasks;
903 
904  private int m_count;
905 
906  internal override bool ShouldNotifyDebuggerOfWaitCompletion
907  {
908  get
909  {
910  if (base.ShouldNotifyDebuggerOfWaitCompletion)
911  {
912  return AnyTaskRequiresNotifyDebuggerOfWaitCompletion(m_tasks);
913  }
914  return false;
915  }
916  }
917 
918  internal WhenAllPromise(Task[] tasks)
919  {
920  if (AsyncCausalityTracer.LoggingOn)
921  {
922  AsyncCausalityTracer.TraceOperationCreation(CausalityTraceLevel.Required, base.Id, "Task.WhenAll", 0uL);
923  }
924  if (s_asyncDebuggingEnabled)
925  {
926  AddToActiveTasks(this);
927  }
928  m_tasks = tasks;
929  m_count = tasks.Length;
930  foreach (Task task in tasks)
931  {
932  if (task.IsCompleted)
933  {
934  Invoke(task);
935  }
936  else
937  {
938  task.AddCompletionAction(this);
939  }
940  }
941  }
942 
943  public void Invoke(Task completedTask)
944  {
945  if (AsyncCausalityTracer.LoggingOn)
946  {
947  AsyncCausalityTracer.TraceOperationRelation(CausalityTraceLevel.Important, base.Id, CausalityRelation.Join);
948  }
949  if (Interlocked.Decrement(ref m_count) != 0)
950  {
951  return;
952  }
953  List<ExceptionDispatchInfo> list = null;
954  Task task = null;
955  for (int i = 0; i < m_tasks.Length; i++)
956  {
957  Task task2 = m_tasks[i];
958  if (task2.IsFaulted)
959  {
960  if (list == null)
961  {
962  list = new List<ExceptionDispatchInfo>();
963  }
964  list.AddRange(task2.GetExceptionDispatchInfos());
965  }
966  else if (task2.IsCanceled && task == null)
967  {
968  task = task2;
969  }
970  if (task2.IsWaitNotificationEnabled)
971  {
972  SetNotificationForWaitCompletion(enabled: true);
973  }
974  else
975  {
976  m_tasks[i] = null;
977  }
978  }
979  if (list != null)
980  {
981  TrySetException(list);
982  return;
983  }
984  if (task != null)
985  {
986  TrySetCanceled(task.CancellationToken, task.GetCancellationExceptionDispatchInfo());
987  return;
988  }
989  if (AsyncCausalityTracer.LoggingOn)
990  {
991  AsyncCausalityTracer.TraceOperationCompletion(CausalityTraceLevel.Required, base.Id, AsyncCausalityStatus.Completed);
992  }
993  if (s_asyncDebuggingEnabled)
994  {
995  RemoveFromActiveTasks(base.Id);
996  }
997  TrySetResult(default(VoidTaskResult));
998  }
999  }
1000 
1001  private sealed class WhenAllPromise<T> : Task<T[]>, ITaskCompletionAction
1002  {
1003  private readonly Task<T>[] m_tasks;
1004 
1005  private int m_count;
1006 
1007  internal override bool ShouldNotifyDebuggerOfWaitCompletion
1008  {
1009  get
1010  {
1011  if (base.ShouldNotifyDebuggerOfWaitCompletion)
1012  {
1013  return AnyTaskRequiresNotifyDebuggerOfWaitCompletion(m_tasks);
1014  }
1015  return false;
1016  }
1017  }
1018 
1019  internal WhenAllPromise(Task<T>[] tasks)
1020  {
1021  m_tasks = tasks;
1022  m_count = tasks.Length;
1023  if (AsyncCausalityTracer.LoggingOn)
1024  {
1025  AsyncCausalityTracer.TraceOperationCreation(CausalityTraceLevel.Required, base.Id, "Task.WhenAll", 0uL);
1026  }
1027  if (s_asyncDebuggingEnabled)
1028  {
1029  AddToActiveTasks(this);
1030  }
1031  foreach (Task<T> task in tasks)
1032  {
1033  if (task.IsCompleted)
1034  {
1035  Invoke(task);
1036  }
1037  else
1038  {
1039  task.AddCompletionAction(this);
1040  }
1041  }
1042  }
1043 
1044  public void Invoke(Task ignored)
1045  {
1046  if (AsyncCausalityTracer.LoggingOn)
1047  {
1048  AsyncCausalityTracer.TraceOperationRelation(CausalityTraceLevel.Important, base.Id, CausalityRelation.Join);
1049  }
1050  if (Interlocked.Decrement(ref m_count) != 0)
1051  {
1052  return;
1053  }
1054  T[] array = new T[m_tasks.Length];
1055  List<ExceptionDispatchInfo> list = null;
1056  Task task = null;
1057  for (int i = 0; i < m_tasks.Length; i++)
1058  {
1059  Task<T> task2 = m_tasks[i];
1060  if (task2.IsFaulted)
1061  {
1062  if (list == null)
1063  {
1064  list = new List<ExceptionDispatchInfo>();
1065  }
1066  list.AddRange(task2.GetExceptionDispatchInfos());
1067  }
1068  else if (task2.IsCanceled)
1069  {
1070  if (task == null)
1071  {
1072  task = task2;
1073  }
1074  }
1075  else
1076  {
1077  array[i] = task2.GetResultCore(waitCompletionNotification: false);
1078  }
1079  if (task2.IsWaitNotificationEnabled)
1080  {
1081  SetNotificationForWaitCompletion(enabled: true);
1082  }
1083  else
1084  {
1085  m_tasks[i] = null;
1086  }
1087  }
1088  if (list != null)
1089  {
1090  TrySetException(list);
1091  return;
1092  }
1093  if (task != null)
1094  {
1095  TrySetCanceled(task.CancellationToken, task.GetCancellationExceptionDispatchInfo());
1096  return;
1097  }
1098  if (AsyncCausalityTracer.LoggingOn)
1099  {
1100  AsyncCausalityTracer.TraceOperationCompletion(CausalityTraceLevel.Required, base.Id, AsyncCausalityStatus.Completed);
1101  }
1102  if (s_asyncDebuggingEnabled)
1103  {
1104  RemoveFromActiveTasks(base.Id);
1105  }
1106  TrySetResult(array);
1107  }
1108  }
1109 
1110  [ThreadStatic]
1111  internal static Task t_currentTask;
1112 
1113  [ThreadStatic]
1114  private static StackGuard t_stackGuard;
1115 
1116  internal static int s_taskIdCounter;
1117 
1118  private static readonly TaskFactory s_factory = new TaskFactory();
1119 
1120  private volatile int m_taskId;
1121 
1122  internal object m_action;
1123 
1124  internal object m_stateObject;
1125 
1126  internal TaskScheduler m_taskScheduler;
1127 
1128  internal readonly Task m_parent;
1129 
1130  internal volatile int m_stateFlags;
1131 
1132  private const int OptionsMask = 65535;
1133 
1134  internal const int TASK_STATE_STARTED = 65536;
1135 
1136  internal const int TASK_STATE_DELEGATE_INVOKED = 131072;
1137 
1138  internal const int TASK_STATE_DISPOSED = 262144;
1139 
1140  internal const int TASK_STATE_EXCEPTIONOBSERVEDBYPARENT = 524288;
1141 
1142  internal const int TASK_STATE_CANCELLATIONACKNOWLEDGED = 1048576;
1143 
1144  internal const int TASK_STATE_FAULTED = 2097152;
1145 
1146  internal const int TASK_STATE_CANCELED = 4194304;
1147 
1148  internal const int TASK_STATE_WAITING_ON_CHILDREN = 8388608;
1149 
1150  internal const int TASK_STATE_RAN_TO_COMPLETION = 16777216;
1151 
1152  internal const int TASK_STATE_WAITINGFORACTIVATION = 33554432;
1153 
1154  internal const int TASK_STATE_COMPLETION_RESERVED = 67108864;
1155 
1156  internal const int TASK_STATE_THREAD_WAS_ABORTED = 134217728;
1157 
1158  internal const int TASK_STATE_WAIT_COMPLETION_NOTIFICATION = 268435456;
1159 
1160  internal const int TASK_STATE_EXECUTIONCONTEXT_IS_NULL = 536870912;
1161 
1162  internal const int TASK_STATE_TASKSCHEDULED_WAS_FIRED = 1073741824;
1163 
1164  private const int TASK_STATE_COMPLETED_MASK = 23068672;
1165 
1166  private const int CANCELLATION_REQUESTED = 1;
1167 
1168  private volatile object m_continuationObject;
1169 
1170  private static readonly object s_taskCompletionSentinel = new object();
1171 
1172  [FriendAccessAllowed]
1173  internal static bool s_asyncDebuggingEnabled;
1174 
1175  private static readonly Dictionary<int, Task> s_currentActiveTasks = new Dictionary<int, Task>();
1176 
1177  private static readonly object s_activeTasksLock = new object();
1178 
1179  internal volatile ContingentProperties m_contingentProperties;
1180 
1181  private static readonly Action<object> s_taskCancelCallback = TaskCancelCallback;
1182 
1183  private static readonly Func<ContingentProperties> s_createContingentProperties = () => new ContingentProperties();
1184 
1185  private static Task s_completedTask;
1186 
1187  private static readonly Predicate<Task> s_IsExceptionObservedByParentPredicate = (Task t) => t.IsExceptionObservedByParent;
1188 
1189  [SecurityCritical]
1190  private static ContextCallback s_ecCallback;
1191 
1192  private static readonly Predicate<object> s_IsTaskContinuationNullPredicate = (object tc) => tc == null;
1193 
1194  private string DebuggerDisplayMethodDescription
1195  {
1196  get
1197  {
1198  Delegate @delegate = (Delegate)m_action;
1199  if ((object)@delegate == null)
1200  {
1201  return "{null}";
1202  }
1203  return @delegate.Method.ToString();
1204  }
1205  }
1206 
1207  internal TaskCreationOptions Options
1208  {
1209  get
1210  {
1211  int stateFlags = m_stateFlags;
1212  return OptionsMethod(stateFlags);
1213  }
1214  }
1215 
1216  internal bool IsWaitNotificationEnabledOrNotRanToCompletion
1217  {
1218  [MethodImpl(MethodImplOptions.AggressiveInlining)]
1219  get
1220  {
1221  return (m_stateFlags & 0x11000000) != 16777216;
1222  }
1223  }
1224 
1225  internal virtual bool ShouldNotifyDebuggerOfWaitCompletion => IsWaitNotificationEnabled;
1226 
1227  internal bool IsWaitNotificationEnabled => (m_stateFlags & 0x10000000) != 0;
1228 
1231  [__DynamicallyInvokable]
1232  public int Id
1233  {
1234  [__DynamicallyInvokable]
1235  get
1236  {
1237  if (m_taskId == 0)
1238  {
1239  int value = NewId();
1240  Interlocked.CompareExchange(ref m_taskId, value, 0);
1241  }
1242  return m_taskId;
1243  }
1244  }
1245 
1248  [__DynamicallyInvokable]
1249  public static int? CurrentId
1250  {
1251  [__DynamicallyInvokable]
1252  get
1253  {
1254  return InternalCurrent?.Id;
1255  }
1256  }
1257 
1258  internal static Task InternalCurrent => t_currentTask;
1259 
1260  internal static StackGuard CurrentStackGuard
1261  {
1262  get
1263  {
1264  StackGuard stackGuard = t_stackGuard;
1265  if (stackGuard == null)
1266  {
1267  stackGuard = (t_stackGuard = new StackGuard());
1268  }
1269  return stackGuard;
1270  }
1271  }
1272 
1275  [__DynamicallyInvokable]
1276  public AggregateException Exception
1277  {
1278  [__DynamicallyInvokable]
1279  get
1280  {
1281  AggregateException result = null;
1282  if (IsFaulted)
1283  {
1284  result = GetExceptions(includeTaskCanceledExceptions: false);
1285  }
1286  return result;
1287  }
1288  }
1289 
1292  [__DynamicallyInvokable]
1293  public TaskStatus Status
1294  {
1295  [__DynamicallyInvokable]
1296  get
1297  {
1298  int stateFlags = m_stateFlags;
1299  if ((stateFlags & 0x200000) != 0)
1300  {
1301  return TaskStatus.Faulted;
1302  }
1303  if ((stateFlags & 0x400000) != 0)
1304  {
1305  return TaskStatus.Canceled;
1306  }
1307  if ((stateFlags & 0x1000000) != 0)
1308  {
1309  return TaskStatus.RanToCompletion;
1310  }
1311  if ((stateFlags & 0x800000) != 0)
1312  {
1313  return TaskStatus.WaitingForChildrenToComplete;
1314  }
1315  if ((stateFlags & 0x20000) != 0)
1316  {
1317  return TaskStatus.Running;
1318  }
1319  if ((stateFlags & 0x10000) != 0)
1320  {
1321  return TaskStatus.WaitingToRun;
1322  }
1323  if ((stateFlags & 0x2000000) != 0)
1324  {
1325  return TaskStatus.WaitingForActivation;
1326  }
1327  return TaskStatus.Created;
1328  }
1329  }
1330 
1334  [__DynamicallyInvokable]
1335  public bool IsCanceled
1336  {
1337  [__DynamicallyInvokable]
1338  get
1339  {
1340  return (m_stateFlags & 0x600000) == 4194304;
1341  }
1342  }
1343 
1344  internal bool IsCancellationRequested
1345  {
1346  get
1347  {
1348  ContingentProperties contingentProperties = m_contingentProperties;
1349  if (contingentProperties != null)
1350  {
1351  if (contingentProperties.m_internalCancellationRequested != 1)
1352  {
1353  return contingentProperties.m_cancellationToken.IsCancellationRequested;
1354  }
1355  return true;
1356  }
1357  return false;
1358  }
1359  }
1360 
1361  internal CancellationToken CancellationToken => m_contingentProperties?.m_cancellationToken ?? default(CancellationToken);
1362 
1363  internal bool IsCancellationAcknowledged => (m_stateFlags & 0x100000) != 0;
1364 
1368  [__DynamicallyInvokable]
1369  public bool IsCompleted
1370  {
1371  [__DynamicallyInvokable]
1372  get
1373  {
1374  int stateFlags = m_stateFlags;
1375  return IsCompletedMethod(stateFlags);
1376  }
1377  }
1378 
1379  internal bool IsRanToCompletion => (m_stateFlags & 0x1600000) == 16777216;
1380 
1383  [__DynamicallyInvokable]
1385  {
1386  [__DynamicallyInvokable]
1387  get
1388  {
1389  return Options & (TaskCreationOptions)(-65281);
1390  }
1391  }
1392 
1396  [__DynamicallyInvokable]
1398  {
1399  [__DynamicallyInvokable]
1400  get
1401  {
1402  if ((m_stateFlags & 0x40000) != 0)
1403  {
1404  throw new ObjectDisposedException(null, Environment.GetResourceString("Task_ThrowIfDisposed"));
1405  }
1406  return CompletedEvent.WaitHandle;
1407  }
1408  }
1409 
1412  [__DynamicallyInvokable]
1413  public object AsyncState
1414  {
1415  [__DynamicallyInvokable]
1416  get
1417  {
1418  return m_stateObject;
1419  }
1420  }
1421 
1425  [__DynamicallyInvokable]
1427  {
1428  [__DynamicallyInvokable]
1429  get
1430  {
1431  return false;
1432  }
1433  }
1434 
1435  internal TaskScheduler ExecutingTaskScheduler => m_taskScheduler;
1436 
1439  [__DynamicallyInvokable]
1440  public static TaskFactory Factory
1441  {
1442  [__DynamicallyInvokable]
1443  get
1444  {
1445  return s_factory;
1446  }
1447  }
1448 
1451  [__DynamicallyInvokable]
1452  public static Task CompletedTask
1453  {
1454  [__DynamicallyInvokable]
1455  get
1456  {
1457  Task task = s_completedTask;
1458  if (task == null)
1459  {
1460  task = (s_completedTask = new Task(canceled: false, (TaskCreationOptions)16384, default(CancellationToken)));
1461  }
1462  return task;
1463  }
1464  }
1465 
1466  internal ManualResetEventSlim CompletedEvent
1467  {
1468  get
1469  {
1470  ContingentProperties contingentProperties = EnsureContingentPropertiesInitialized(needsProtection: true);
1471  if (contingentProperties.m_completionEvent == null)
1472  {
1473  bool isCompleted = IsCompleted;
1474  ManualResetEventSlim manualResetEventSlim = new ManualResetEventSlim(isCompleted);
1475  if (Interlocked.CompareExchange(ref contingentProperties.m_completionEvent, manualResetEventSlim, null) != null)
1476  {
1477  manualResetEventSlim.Dispose();
1478  }
1479  else if (!isCompleted && IsCompleted)
1480  {
1481  manualResetEventSlim.Set();
1482  }
1483  }
1484  return contingentProperties.m_completionEvent;
1485  }
1486  }
1487 
1488  internal bool IsSelfReplicatingRoot => (Options & (TaskCreationOptions)2304) == (TaskCreationOptions)2048;
1489 
1490  internal bool IsChildReplica => (Options & (TaskCreationOptions)256) != TaskCreationOptions.None;
1491 
1492  internal int ActiveChildCount
1493  {
1494  get
1495  {
1496  ContingentProperties contingentProperties = m_contingentProperties;
1497  if (contingentProperties == null)
1498  {
1499  return 0;
1500  }
1501  return contingentProperties.m_completionCountdown - 1;
1502  }
1503  }
1504 
1505  internal bool ExceptionRecorded
1506  {
1507  get
1508  {
1509  ContingentProperties contingentProperties = m_contingentProperties;
1510  if (contingentProperties != null && contingentProperties.m_exceptionsHolder != null)
1511  {
1512  return contingentProperties.m_exceptionsHolder.ContainsFaultList;
1513  }
1514  return false;
1515  }
1516  }
1517 
1521  [__DynamicallyInvokable]
1522  public bool IsFaulted
1523  {
1524  [__DynamicallyInvokable]
1525  get
1526  {
1527  return (m_stateFlags & 0x200000) != 0;
1528  }
1529  }
1530 
1531  internal ExecutionContext CapturedContext
1532  {
1533  get
1534  {
1535  if ((m_stateFlags & 0x20000000) == 536870912)
1536  {
1537  return null;
1538  }
1539  ContingentProperties contingentProperties = m_contingentProperties;
1540  if (contingentProperties != null && contingentProperties.m_capturedContext != null)
1541  {
1542  return contingentProperties.m_capturedContext;
1543  }
1544  return ExecutionContext.PreAllocatedDefault;
1545  }
1546  set
1547  {
1548  if (value == null)
1549  {
1550  m_stateFlags |= 536870912;
1551  }
1552  else if (!value.IsPreAllocatedDefault)
1553  {
1554  EnsureContingentPropertiesInitialized(needsProtection: false).m_capturedContext = value;
1555  }
1556  }
1557  }
1558 
1559  internal bool IsExceptionObservedByParent => (m_stateFlags & 0x80000) != 0;
1560 
1561  internal bool IsDelegateInvoked => (m_stateFlags & 0x20000) != 0;
1562 
1563  internal virtual object SavedStateForNextReplica
1564  {
1565  get
1566  {
1567  return null;
1568  }
1569  set
1570  {
1571  }
1572  }
1573 
1574  internal virtual object SavedStateFromPreviousReplica
1575  {
1576  get
1577  {
1578  return null;
1579  }
1580  set
1581  {
1582  }
1583  }
1584 
1585  internal virtual Task HandedOverChildReplica
1586  {
1587  get
1588  {
1589  return null;
1590  }
1591  set
1592  {
1593  }
1594  }
1595 
1596  [FriendAccessAllowed]
1597  internal static bool AddToActiveTasks(Task task)
1598  {
1599  lock (s_activeTasksLock)
1600  {
1601  s_currentActiveTasks[task.Id] = task;
1602  }
1603  return true;
1604  }
1605 
1606  [FriendAccessAllowed]
1607  internal static void RemoveFromActiveTasks(int taskId)
1608  {
1609  lock (s_activeTasksLock)
1610  {
1611  s_currentActiveTasks.Remove(taskId);
1612  }
1613  }
1614 
1615  internal Task(bool canceled, TaskCreationOptions creationOptions, CancellationToken ct)
1616  {
1617  if (canceled)
1618  {
1619  m_stateFlags = (int)((TaskCreationOptions)5242880 | creationOptions);
1620  ContingentProperties contingentProperties = m_contingentProperties = new ContingentProperties();
1621  contingentProperties.m_cancellationToken = ct;
1622  contingentProperties.m_internalCancellationRequested = 1;
1623  }
1624  else
1625  {
1626  m_stateFlags = (int)((TaskCreationOptions)16777216 | creationOptions);
1627  }
1628  }
1629 
1630  internal Task()
1631  {
1632  m_stateFlags = 33555456;
1633  }
1634 
1635  internal Task(object state, TaskCreationOptions creationOptions, bool promiseStyle)
1636  {
1637  if ((creationOptions & ~(TaskCreationOptions.AttachedToParent | TaskCreationOptions.RunContinuationsAsynchronously)) != 0)
1638  {
1639  throw new ArgumentOutOfRangeException("creationOptions");
1640  }
1641  if ((creationOptions & TaskCreationOptions.AttachedToParent) != 0)
1642  {
1643  m_parent = InternalCurrent;
1644  }
1645  TaskConstructorCore(null, state, default(CancellationToken), creationOptions, InternalTaskOptions.PromiseTask, null);
1646  }
1647 
1651  [MethodImpl(MethodImplOptions.NoInlining)]
1652  [__DynamicallyInvokable]
1653  public Task(Action action)
1654  : this(action, null, null, default(CancellationToken), TaskCreationOptions.None, InternalTaskOptions.None, null)
1655  {
1656  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1657  PossiblyCaptureContext(ref stackMark);
1658  }
1659 
1665  [MethodImpl(MethodImplOptions.NoInlining)]
1666  [__DynamicallyInvokable]
1667  public Task(Action action, CancellationToken cancellationToken)
1668  : this(action, null, null, cancellationToken, TaskCreationOptions.None, InternalTaskOptions.None, null)
1669  {
1670  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1671  PossiblyCaptureContext(ref stackMark);
1672  }
1673 
1679  [MethodImpl(MethodImplOptions.NoInlining)]
1680  [__DynamicallyInvokable]
1681  public Task(Action action, TaskCreationOptions creationOptions)
1682  : this(action, null, InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, InternalTaskOptions.None, null)
1683  {
1684  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1685  PossiblyCaptureContext(ref stackMark);
1686  }
1687 
1695  [MethodImpl(MethodImplOptions.NoInlining)]
1696  [__DynamicallyInvokable]
1697  public Task(Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
1698  : this(action, null, InternalCurrentIfAttached(creationOptions), cancellationToken, creationOptions, InternalTaskOptions.None, null)
1699  {
1700  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1701  PossiblyCaptureContext(ref stackMark);
1702  }
1703 
1708  [MethodImpl(MethodImplOptions.NoInlining)]
1709  [__DynamicallyInvokable]
1710  public Task(Action<object> action, object state)
1711  : this(action, state, null, default(CancellationToken), TaskCreationOptions.None, InternalTaskOptions.None, null)
1712  {
1713  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1714  PossiblyCaptureContext(ref stackMark);
1715  }
1716 
1723  [MethodImpl(MethodImplOptions.NoInlining)]
1724  [__DynamicallyInvokable]
1725  public Task(Action<object> action, object state, CancellationToken cancellationToken)
1726  : this(action, state, null, cancellationToken, TaskCreationOptions.None, InternalTaskOptions.None, null)
1727  {
1728  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1729  PossiblyCaptureContext(ref stackMark);
1730  }
1731 
1738  [MethodImpl(MethodImplOptions.NoInlining)]
1739  [__DynamicallyInvokable]
1740  public Task(Action<object> action, object state, TaskCreationOptions creationOptions)
1741  : this(action, state, InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, InternalTaskOptions.None, null)
1742  {
1743  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1744  PossiblyCaptureContext(ref stackMark);
1745  }
1746 
1755  [MethodImpl(MethodImplOptions.NoInlining)]
1756  [__DynamicallyInvokable]
1757  public Task(Action<object> action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
1758  : this(action, state, InternalCurrentIfAttached(creationOptions), cancellationToken, creationOptions, InternalTaskOptions.None, null)
1759  {
1760  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1761  PossiblyCaptureContext(ref stackMark);
1762  }
1763 
1764  internal Task(Action<object> action, object state, Task parent, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler, ref StackCrawlMark stackMark)
1765  : this(action, state, parent, cancellationToken, creationOptions, internalOptions, scheduler)
1766  {
1767  PossiblyCaptureContext(ref stackMark);
1768  }
1769 
1770  internal Task(Delegate action, object state, Task parent, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler)
1771  {
1772  if ((object)action == null)
1773  {
1774  throw new ArgumentNullException("action");
1775  }
1776  if ((creationOptions & TaskCreationOptions.AttachedToParent) != 0 || (internalOptions & InternalTaskOptions.SelfReplicating) != 0)
1777  {
1778  m_parent = parent;
1779  }
1780  TaskConstructorCore(action, state, cancellationToken, creationOptions, internalOptions, scheduler);
1781  }
1782 
1783  internal void TaskConstructorCore(object action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler)
1784  {
1785  m_action = action;
1786  m_stateObject = state;
1787  m_taskScheduler = scheduler;
1788  if ((creationOptions & ~(TaskCreationOptions.PreferFairness | TaskCreationOptions.LongRunning | TaskCreationOptions.AttachedToParent | TaskCreationOptions.DenyChildAttach | TaskCreationOptions.HideScheduler | TaskCreationOptions.RunContinuationsAsynchronously)) != 0)
1789  {
1790  throw new ArgumentOutOfRangeException("creationOptions");
1791  }
1792  if ((creationOptions & TaskCreationOptions.LongRunning) != 0 && (internalOptions & InternalTaskOptions.SelfReplicating) != 0)
1793  {
1794  throw new InvalidOperationException(Environment.GetResourceString("Task_ctor_LRandSR"));
1795  }
1796  int num = (int)creationOptions | (int)internalOptions;
1797  if (m_action == null || (internalOptions & InternalTaskOptions.ContinuationTask) != 0)
1798  {
1799  num |= 0x2000000;
1800  }
1801  m_stateFlags = num;
1802  if (m_parent != null && (creationOptions & TaskCreationOptions.AttachedToParent) != 0 && (m_parent.CreationOptions & TaskCreationOptions.DenyChildAttach) == TaskCreationOptions.None)
1803  {
1804  m_parent.AddNewChild();
1805  }
1806  if (cancellationToken.CanBeCanceled)
1807  {
1808  AssignCancellationToken(cancellationToken, null, null);
1809  }
1810  }
1811 
1812  private void AssignCancellationToken(CancellationToken cancellationToken, Task antecedent, TaskContinuation continuation)
1813  {
1814  ContingentProperties contingentProperties = EnsureContingentPropertiesInitialized(needsProtection: false);
1815  contingentProperties.m_cancellationToken = cancellationToken;
1816  try
1817  {
1818  if (AppContextSwitches.ThrowExceptionIfDisposedCancellationTokenSource)
1819  {
1820  cancellationToken.ThrowIfSourceDisposed();
1821  }
1822  if ((Options & (TaskCreationOptions)13312) == TaskCreationOptions.None)
1823  {
1824  if (cancellationToken.IsCancellationRequested)
1825  {
1826  InternalCancel(bCancelNonExecutingOnly: false);
1827  }
1828  else
1829  {
1830  CancellationTokenRegistration value = (antecedent != null) ? cancellationToken.InternalRegisterWithoutEC(s_taskCancelCallback, new Tuple<Task, Task, TaskContinuation>(this, antecedent, continuation)) : cancellationToken.InternalRegisterWithoutEC(s_taskCancelCallback, this);
1831  contingentProperties.m_cancellationRegistration = new Shared<CancellationTokenRegistration>(value);
1832  }
1833  }
1834  }
1835  catch
1836  {
1837  if (m_parent != null && (Options & TaskCreationOptions.AttachedToParent) != 0 && (m_parent.Options & TaskCreationOptions.DenyChildAttach) == TaskCreationOptions.None)
1838  {
1839  m_parent.DisregardChild();
1840  }
1841  throw;
1842  }
1843  }
1844 
1845  private static void TaskCancelCallback(object o)
1846  {
1847  Task task = o as Task;
1848  if (task == null)
1849  {
1850  Tuple<Task, Task, TaskContinuation> tuple = o as Tuple<Task, Task, TaskContinuation>;
1851  if (tuple != null)
1852  {
1853  task = tuple.Item1;
1854  Task item = tuple.Item2;
1855  TaskContinuation item2 = tuple.Item3;
1856  item.RemoveContinuation(item2);
1857  }
1858  }
1859  task.InternalCancel(bCancelNonExecutingOnly: false);
1860  }
1861 
1862  [SecuritySafeCritical]
1863  internal void PossiblyCaptureContext(ref StackCrawlMark stackMark)
1864  {
1865  CapturedContext = ExecutionContext.Capture(ref stackMark, ExecutionContext.CaptureOptions.IgnoreSyncCtx | ExecutionContext.CaptureOptions.OptimizeDefaultCase);
1866  }
1867 
1868  internal static TaskCreationOptions OptionsMethod(int flags)
1869  {
1870  return (TaskCreationOptions)(flags & 0xFFFF);
1871  }
1872 
1873  internal bool AtomicStateUpdate(int newBits, int illegalBits)
1874  {
1875  SpinWait spinWait = default(SpinWait);
1876  while (true)
1877  {
1878  int stateFlags = m_stateFlags;
1879  if ((stateFlags & illegalBits) != 0)
1880  {
1881  return false;
1882  }
1883  if (Interlocked.CompareExchange(ref m_stateFlags, stateFlags | newBits, stateFlags) == stateFlags)
1884  {
1885  break;
1886  }
1887  spinWait.SpinOnce();
1888  }
1889  return true;
1890  }
1891 
1892  internal bool AtomicStateUpdate(int newBits, int illegalBits, ref int oldFlags)
1893  {
1894  SpinWait spinWait = default(SpinWait);
1895  while (true)
1896  {
1897  oldFlags = m_stateFlags;
1898  if ((oldFlags & illegalBits) != 0)
1899  {
1900  return false;
1901  }
1902  if (Interlocked.CompareExchange(ref m_stateFlags, oldFlags | newBits, oldFlags) == oldFlags)
1903  {
1904  break;
1905  }
1906  spinWait.SpinOnce();
1907  }
1908  return true;
1909  }
1910 
1911  internal void SetNotificationForWaitCompletion(bool enabled)
1912  {
1913  if (enabled)
1914  {
1915  bool flag = AtomicStateUpdate(268435456, 90177536);
1916  return;
1917  }
1918  SpinWait spinWait = default(SpinWait);
1919  while (true)
1920  {
1921  int stateFlags = m_stateFlags;
1922  int value = stateFlags & -268435457;
1923  if (Interlocked.CompareExchange(ref m_stateFlags, value, stateFlags) != stateFlags)
1924  {
1925  spinWait.SpinOnce();
1926  continue;
1927  }
1928  break;
1929  }
1930  }
1931 
1932  internal bool NotifyDebuggerOfWaitCompletionIfNecessary()
1933  {
1934  if (IsWaitNotificationEnabled && ShouldNotifyDebuggerOfWaitCompletion)
1935  {
1936  NotifyDebuggerOfWaitCompletion();
1937  return true;
1938  }
1939  return false;
1940  }
1941 
1942  internal static bool AnyTaskRequiresNotifyDebuggerOfWaitCompletion(Task[] tasks)
1943  {
1944  foreach (Task task in tasks)
1945  {
1946  if (task != null && task.IsWaitNotificationEnabled && task.ShouldNotifyDebuggerOfWaitCompletion)
1947  {
1948  return true;
1949  }
1950  }
1951  return false;
1952  }
1953 
1954  [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
1955  private void NotifyDebuggerOfWaitCompletion()
1956  {
1957  SetNotificationForWaitCompletion(enabled: false);
1958  }
1959 
1960  internal bool MarkStarted()
1961  {
1962  return AtomicStateUpdate(65536, 4259840);
1963  }
1964 
1965  [MethodImpl(MethodImplOptions.AggressiveInlining)]
1966  internal bool FireTaskScheduledIfNeeded(TaskScheduler ts)
1967  {
1968  TplEtwProvider log = TplEtwProvider.Log;
1969  if (log.IsEnabled() && (m_stateFlags & 0x40000000) == 0)
1970  {
1971  m_stateFlags |= 1073741824;
1972  Task internalCurrent = InternalCurrent;
1973  Task parent = m_parent;
1974  log.TaskScheduled(ts.Id, internalCurrent?.Id ?? 0, Id, parent?.Id ?? 0, (int)Options, Thread.GetDomainID());
1975  return true;
1976  }
1977  return false;
1978  }
1979 
1980  internal void AddNewChild()
1981  {
1982  ContingentProperties contingentProperties = EnsureContingentPropertiesInitialized(needsProtection: true);
1983  if (contingentProperties.m_completionCountdown == 1 && !IsSelfReplicatingRoot)
1984  {
1985  contingentProperties.m_completionCountdown++;
1986  }
1987  else
1988  {
1989  Interlocked.Increment(ref contingentProperties.m_completionCountdown);
1990  }
1991  }
1992 
1993  internal void DisregardChild()
1994  {
1995  ContingentProperties contingentProperties = EnsureContingentPropertiesInitialized(needsProtection: true);
1996  Interlocked.Decrement(ref contingentProperties.m_completionCountdown);
1997  }
1998 
2002  [__DynamicallyInvokable]
2003  public void Start()
2004  {
2006  }
2007 
2014  [__DynamicallyInvokable]
2015  public void Start(TaskScheduler scheduler)
2016  {
2017  int stateFlags = m_stateFlags;
2018  if (IsCompletedMethod(stateFlags))
2019  {
2020  throw new InvalidOperationException(Environment.GetResourceString("Task_Start_TaskCompleted"));
2021  }
2022  if (scheduler == null)
2023  {
2024  throw new ArgumentNullException("scheduler");
2025  }
2026  TaskCreationOptions taskCreationOptions = OptionsMethod(stateFlags);
2027  if ((taskCreationOptions & (TaskCreationOptions)1024) != 0)
2028  {
2029  throw new InvalidOperationException(Environment.GetResourceString("Task_Start_Promise"));
2030  }
2031  if ((taskCreationOptions & (TaskCreationOptions)512) != 0)
2032  {
2033  throw new InvalidOperationException(Environment.GetResourceString("Task_Start_ContinuationTask"));
2034  }
2035  if (Interlocked.CompareExchange(ref m_taskScheduler, scheduler, null) != null)
2036  {
2037  throw new InvalidOperationException(Environment.GetResourceString("Task_Start_AlreadyStarted"));
2038  }
2039  ScheduleAndStart(needsProtection: true);
2040  }
2041 
2045  [__DynamicallyInvokable]
2046  public void RunSynchronously()
2047  {
2048  InternalRunSynchronously(TaskScheduler.Current, waitForCompletion: true);
2049  }
2050 
2056  [__DynamicallyInvokable]
2057  public void RunSynchronously(TaskScheduler scheduler)
2058  {
2059  if (scheduler == null)
2060  {
2061  throw new ArgumentNullException("scheduler");
2062  }
2063  InternalRunSynchronously(scheduler, waitForCompletion: true);
2064  }
2065 
2066  [SecuritySafeCritical]
2067  internal void InternalRunSynchronously(TaskScheduler scheduler, bool waitForCompletion)
2068  {
2069  int stateFlags = m_stateFlags;
2070  TaskCreationOptions taskCreationOptions = OptionsMethod(stateFlags);
2071  if ((taskCreationOptions & (TaskCreationOptions)512) != 0)
2072  {
2073  throw new InvalidOperationException(Environment.GetResourceString("Task_RunSynchronously_Continuation"));
2074  }
2075  if ((taskCreationOptions & (TaskCreationOptions)1024) != 0)
2076  {
2077  throw new InvalidOperationException(Environment.GetResourceString("Task_RunSynchronously_Promise"));
2078  }
2079  if (IsCompletedMethod(stateFlags))
2080  {
2081  throw new InvalidOperationException(Environment.GetResourceString("Task_RunSynchronously_TaskCompleted"));
2082  }
2083  if (Interlocked.CompareExchange(ref m_taskScheduler, scheduler, null) != null)
2084  {
2085  throw new InvalidOperationException(Environment.GetResourceString("Task_RunSynchronously_AlreadyStarted"));
2086  }
2087  if (MarkStarted())
2088  {
2089  bool flag = false;
2090  try
2091  {
2092  if (!scheduler.TryRunInline(this, taskWasPreviouslyQueued: false))
2093  {
2094  scheduler.InternalQueueTask(this);
2095  flag = true;
2096  }
2097  if (waitForCompletion && !IsCompleted)
2098  {
2099  SpinThenBlockingWait(-1, default(CancellationToken));
2100  }
2101  }
2102  catch (Exception ex)
2103  {
2104  if (!flag && !(ex is ThreadAbortException))
2105  {
2106  TaskSchedulerException ex2 = new TaskSchedulerException(ex);
2107  AddException(ex2);
2108  Finish(bUserDelegateExecuted: false);
2109  m_contingentProperties.m_exceptionsHolder.MarkAsHandled(calledFromFinalizer: false);
2110  throw ex2;
2111  }
2112  throw;
2113  }
2114  return;
2115  }
2116  throw new InvalidOperationException(Environment.GetResourceString("Task_RunSynchronously_TaskCompleted"));
2117  }
2118 
2119  internal static Task InternalStartNew(Task creatingTask, Delegate action, object state, CancellationToken cancellationToken, TaskScheduler scheduler, TaskCreationOptions options, InternalTaskOptions internalOptions, ref StackCrawlMark stackMark)
2120  {
2121  if (scheduler == null)
2122  {
2123  throw new ArgumentNullException("scheduler");
2124  }
2125  Task task = new Task(action, state, creatingTask, cancellationToken, options, internalOptions | InternalTaskOptions.QueuedByRuntime, scheduler);
2126  task.PossiblyCaptureContext(ref stackMark);
2127  task.ScheduleAndStart(needsProtection: false);
2128  return task;
2129  }
2130 
2131  internal static int NewId()
2132  {
2133  int num = 0;
2134  do
2135  {
2136  num = Interlocked.Increment(ref s_taskIdCounter);
2137  }
2138  while (num == 0);
2139  TplEtwProvider.Log.NewID(num);
2140  return num;
2141  }
2142 
2143  internal static Task InternalCurrentIfAttached(TaskCreationOptions creationOptions)
2144  {
2145  if ((creationOptions & TaskCreationOptions.AttachedToParent) == TaskCreationOptions.None)
2146  {
2147  return null;
2148  }
2149  return InternalCurrent;
2150  }
2151 
2152  internal ContingentProperties EnsureContingentPropertiesInitialized(bool needsProtection)
2153  {
2154  ContingentProperties contingentProperties = m_contingentProperties;
2155  if (contingentProperties == null)
2156  {
2157  return EnsureContingentPropertiesInitializedCore(needsProtection);
2158  }
2159  return contingentProperties;
2160  }
2161 
2162  private ContingentProperties EnsureContingentPropertiesInitializedCore(bool needsProtection)
2163  {
2164  if (needsProtection)
2165  {
2166  return LazyInitializer.EnsureInitialized(ref m_contingentProperties, s_createContingentProperties);
2167  }
2168  return m_contingentProperties = new ContingentProperties();
2169  }
2170 
2171  private static bool IsCompletedMethod(int flags)
2172  {
2173  return (flags & 0x1600000) != 0;
2174  }
2175 
2176  private static ExecutionContext CopyExecutionContext(ExecutionContext capturedContext)
2177  {
2178  if (capturedContext == null)
2179  {
2180  return null;
2181  }
2182  if (capturedContext.IsPreAllocatedDefault)
2183  {
2184  return ExecutionContext.PreAllocatedDefault;
2185  }
2186  return capturedContext.CreateCopy();
2187  }
2188 
2191  public void Dispose()
2192  {
2193  Dispose(disposing: true);
2194  GC.SuppressFinalize(this);
2195  }
2196 
2200  protected virtual void Dispose(bool disposing)
2201  {
2202  if (disposing)
2203  {
2204  if ((Options & (TaskCreationOptions)16384) != 0)
2205  {
2206  return;
2207  }
2208  if (!IsCompleted)
2209  {
2210  throw new InvalidOperationException(Environment.GetResourceString("Task_Dispose_NotCompleted"));
2211  }
2212  ContingentProperties contingentProperties = m_contingentProperties;
2213  if (contingentProperties != null)
2214  {
2215  ManualResetEventSlim completionEvent = contingentProperties.m_completionEvent;
2216  if (completionEvent != null)
2217  {
2218  contingentProperties.m_completionEvent = null;
2219  if (!completionEvent.IsSet)
2220  {
2221  completionEvent.Set();
2222  }
2223  completionEvent.Dispose();
2224  }
2225  }
2226  }
2227  m_stateFlags |= 262144;
2228  }
2229 
2230  [SecuritySafeCritical]
2231  internal void ScheduleAndStart(bool needsProtection)
2232  {
2233  if (needsProtection)
2234  {
2235  if (!MarkStarted())
2236  {
2237  return;
2238  }
2239  }
2240  else
2241  {
2242  m_stateFlags |= 65536;
2243  }
2244  if (s_asyncDebuggingEnabled)
2245  {
2246  AddToActiveTasks(this);
2247  }
2248  if (AsyncCausalityTracer.LoggingOn && (Options & (TaskCreationOptions)512) == TaskCreationOptions.None)
2249  {
2250  AsyncCausalityTracer.TraceOperationCreation(CausalityTraceLevel.Required, Id, "Task: " + ((Delegate)m_action).Method.Name, 0uL);
2251  }
2252  try
2253  {
2254  m_taskScheduler.InternalQueueTask(this);
2255  }
2256  catch (ThreadAbortException exceptionObject)
2257  {
2258  AddException(exceptionObject);
2259  FinishThreadAbortedTask(bTAEAddedToExceptionHolder: true, delegateRan: false);
2260  }
2261  catch (Exception innerException)
2262  {
2263  TaskSchedulerException ex = new TaskSchedulerException(innerException);
2264  AddException(ex);
2265  Finish(bUserDelegateExecuted: false);
2266  if ((Options & (TaskCreationOptions)512) == TaskCreationOptions.None)
2267  {
2268  m_contingentProperties.m_exceptionsHolder.MarkAsHandled(calledFromFinalizer: false);
2269  }
2270  throw ex;
2271  }
2272  }
2273 
2274  internal void AddException(object exceptionObject)
2275  {
2276  AddException(exceptionObject, representsCancellation: false);
2277  }
2278 
2279  internal void AddException(object exceptionObject, bool representsCancellation)
2280  {
2281  ContingentProperties contingentProperties = EnsureContingentPropertiesInitialized(needsProtection: true);
2282  if (contingentProperties.m_exceptionsHolder == null)
2283  {
2284  TaskExceptionHolder taskExceptionHolder = new TaskExceptionHolder(this);
2285  if (Interlocked.CompareExchange(ref contingentProperties.m_exceptionsHolder, taskExceptionHolder, null) != null)
2286  {
2287  taskExceptionHolder.MarkAsHandled(calledFromFinalizer: false);
2288  }
2289  }
2290  lock (contingentProperties)
2291  {
2292  contingentProperties.m_exceptionsHolder.Add(exceptionObject, representsCancellation);
2293  }
2294  }
2295 
2296  private AggregateException GetExceptions(bool includeTaskCanceledExceptions)
2297  {
2298  Exception ex = null;
2299  if (includeTaskCanceledExceptions && IsCanceled)
2300  {
2301  ex = new TaskCanceledException(this);
2302  }
2303  if (ExceptionRecorded)
2304  {
2305  return m_contingentProperties.m_exceptionsHolder.CreateExceptionObject(calledFromFinalizer: false, ex);
2306  }
2307  if (ex != null)
2308  {
2309  return new AggregateException(ex);
2310  }
2311  return null;
2312  }
2313 
2314  internal ReadOnlyCollection<ExceptionDispatchInfo> GetExceptionDispatchInfos()
2315  {
2316  if (!IsFaulted || !ExceptionRecorded)
2317  {
2319  }
2320  return m_contingentProperties.m_exceptionsHolder.GetExceptionDispatchInfos();
2321  }
2322 
2323  internal ExceptionDispatchInfo GetCancellationExceptionDispatchInfo()
2324  {
2325  ContingentProperties contingentProperties = m_contingentProperties;
2326  if (contingentProperties == null)
2327  {
2328  return null;
2329  }
2330  return contingentProperties.m_exceptionsHolder?.GetCancellationExceptionDispatchInfo();
2331  }
2332 
2333  internal void ThrowIfExceptional(bool includeTaskCanceledExceptions)
2334  {
2335  Exception exceptions = GetExceptions(includeTaskCanceledExceptions);
2336  if (exceptions != null)
2337  {
2338  UpdateExceptionObservedStatus();
2339  throw exceptions;
2340  }
2341  }
2342 
2343  internal void UpdateExceptionObservedStatus()
2344  {
2345  if (m_parent != null && (Options & TaskCreationOptions.AttachedToParent) != 0 && (m_parent.CreationOptions & TaskCreationOptions.DenyChildAttach) == TaskCreationOptions.None && InternalCurrent == m_parent)
2346  {
2347  m_stateFlags |= 524288;
2348  }
2349  }
2350 
2351  internal void Finish(bool bUserDelegateExecuted)
2352  {
2353  if (!bUserDelegateExecuted)
2354  {
2355  FinishStageTwo();
2356  return;
2357  }
2358  ContingentProperties contingentProperties = m_contingentProperties;
2359  if (contingentProperties == null || (contingentProperties.m_completionCountdown == 1 && !IsSelfReplicatingRoot) || Interlocked.Decrement(ref contingentProperties.m_completionCountdown) == 0)
2360  {
2361  FinishStageTwo();
2362  }
2363  else
2364  {
2365  AtomicStateUpdate(8388608, 23068672);
2366  }
2367  List<Task> list = (contingentProperties != null) ? contingentProperties.m_exceptionalChildren : null;
2368  if (list != null)
2369  {
2370  lock (list)
2371  {
2372  list.RemoveAll(s_IsExceptionObservedByParentPredicate);
2373  }
2374  }
2375  }
2376 
2377  internal void FinishStageTwo()
2378  {
2379  AddExceptionsFromChildren();
2380  int num;
2381  if (ExceptionRecorded)
2382  {
2383  num = 2097152;
2384  if (AsyncCausalityTracer.LoggingOn)
2385  {
2386  AsyncCausalityTracer.TraceOperationCompletion(CausalityTraceLevel.Required, Id, AsyncCausalityStatus.Error);
2387  }
2388  if (s_asyncDebuggingEnabled)
2389  {
2390  RemoveFromActiveTasks(Id);
2391  }
2392  }
2393  else if (IsCancellationRequested && IsCancellationAcknowledged)
2394  {
2395  num = 4194304;
2396  if (AsyncCausalityTracer.LoggingOn)
2397  {
2398  AsyncCausalityTracer.TraceOperationCompletion(CausalityTraceLevel.Required, Id, AsyncCausalityStatus.Canceled);
2399  }
2400  if (s_asyncDebuggingEnabled)
2401  {
2402  RemoveFromActiveTasks(Id);
2403  }
2404  }
2405  else
2406  {
2407  num = 16777216;
2408  if (AsyncCausalityTracer.LoggingOn)
2409  {
2410  AsyncCausalityTracer.TraceOperationCompletion(CausalityTraceLevel.Required, Id, AsyncCausalityStatus.Completed);
2411  }
2412  if (s_asyncDebuggingEnabled)
2413  {
2414  RemoveFromActiveTasks(Id);
2415  }
2416  }
2417  Interlocked.Exchange(ref m_stateFlags, m_stateFlags | num);
2418  ContingentProperties contingentProperties = m_contingentProperties;
2419  if (contingentProperties != null)
2420  {
2421  contingentProperties.SetCompleted();
2422  contingentProperties.DeregisterCancellationCallback();
2423  }
2424  FinishStageThree();
2425  }
2426 
2427  internal void FinishStageThree()
2428  {
2429  m_action = null;
2430  if (m_parent != null && (m_parent.CreationOptions & TaskCreationOptions.DenyChildAttach) == TaskCreationOptions.None && (m_stateFlags & 0xFFFF & 4) != 0)
2431  {
2432  m_parent.ProcessChildCompletion(this);
2433  }
2434  FinishContinuations();
2435  }
2436 
2437  internal void ProcessChildCompletion(Task childTask)
2438  {
2439  ContingentProperties contingentProperties = m_contingentProperties;
2440  if (childTask.IsFaulted && !childTask.IsExceptionObservedByParent)
2441  {
2442  if (contingentProperties.m_exceptionalChildren == null)
2443  {
2444  Interlocked.CompareExchange(ref contingentProperties.m_exceptionalChildren, new List<Task>(), null);
2445  }
2446  List<Task> exceptionalChildren = contingentProperties.m_exceptionalChildren;
2447  if (exceptionalChildren != null)
2448  {
2449  lock (exceptionalChildren)
2450  {
2451  exceptionalChildren.Add(childTask);
2452  }
2453  }
2454  }
2455  if (Interlocked.Decrement(ref contingentProperties.m_completionCountdown) == 0)
2456  {
2457  FinishStageTwo();
2458  }
2459  }
2460 
2461  internal void AddExceptionsFromChildren()
2462  {
2463  ContingentProperties contingentProperties = m_contingentProperties;
2464  List<Task> list = (contingentProperties != null) ? contingentProperties.m_exceptionalChildren : null;
2465  if (list != null)
2466  {
2467  lock (list)
2468  {
2469  foreach (Task item in list)
2470  {
2471  if (item.IsFaulted && !item.IsExceptionObservedByParent)
2472  {
2473  TaskExceptionHolder exceptionsHolder = item.m_contingentProperties.m_exceptionsHolder;
2474  AddException(exceptionsHolder.CreateExceptionObject(calledFromFinalizer: false, null));
2475  }
2476  }
2477  }
2478  contingentProperties.m_exceptionalChildren = null;
2479  }
2480  }
2481 
2482  internal void FinishThreadAbortedTask(bool bTAEAddedToExceptionHolder, bool delegateRan)
2483  {
2484  if (bTAEAddedToExceptionHolder)
2485  {
2486  m_contingentProperties.m_exceptionsHolder.MarkAsHandled(calledFromFinalizer: false);
2487  }
2488  if (AtomicStateUpdate(134217728, 157286400))
2489  {
2490  Finish(delegateRan);
2491  }
2492  }
2493 
2494  private void Execute()
2495  {
2496  if (IsSelfReplicatingRoot)
2497  {
2498  ExecuteSelfReplicating(this);
2499  }
2500  else
2501  {
2502  try
2503  {
2504  InnerInvoke();
2505  }
2506  catch (ThreadAbortException unhandledException)
2507  {
2508  if (!IsChildReplica)
2509  {
2510  HandleException(unhandledException);
2511  FinishThreadAbortedTask(bTAEAddedToExceptionHolder: true, delegateRan: true);
2512  }
2513  }
2514  catch (Exception unhandledException2)
2515  {
2516  HandleException(unhandledException2);
2517  }
2518  }
2519  }
2520 
2521  internal virtual bool ShouldReplicate()
2522  {
2523  return true;
2524  }
2525 
2526  internal virtual Task CreateReplicaTask(Action<object> taskReplicaDelegate, object stateObject, Task parentTask, TaskScheduler taskScheduler, TaskCreationOptions creationOptionsForReplica, InternalTaskOptions internalOptionsForReplica)
2527  {
2528  return new Task(taskReplicaDelegate, stateObject, parentTask, default(CancellationToken), creationOptionsForReplica, internalOptionsForReplica, parentTask.ExecutingTaskScheduler);
2529  }
2530 
2531  private static void ExecuteSelfReplicating(Task root)
2532  {
2533  TaskCreationOptions creationOptionsForReplicas = root.CreationOptions | TaskCreationOptions.AttachedToParent;
2534  InternalTaskOptions internalOptionsForReplicas = InternalTaskOptions.ChildReplica | InternalTaskOptions.SelfReplicating | InternalTaskOptions.QueuedByRuntime;
2535  bool replicasAreQuitting = false;
2536  Action<object> taskReplicaDelegate = null;
2537  taskReplicaDelegate = delegate
2538  {
2539  Task internalCurrent = InternalCurrent;
2540  Task task = internalCurrent.HandedOverChildReplica;
2541  if (task == null)
2542  {
2543  if (!root.ShouldReplicate() || Volatile.Read(ref replicasAreQuitting))
2544  {
2545  return;
2546  }
2547  ExecutionContext capturedContext = root.CapturedContext;
2548  task = root.CreateReplicaTask(taskReplicaDelegate, root.m_stateObject, root, root.ExecutingTaskScheduler, creationOptionsForReplicas, internalOptionsForReplicas);
2549  task.CapturedContext = CopyExecutionContext(capturedContext);
2550  task.ScheduleAndStart(needsProtection: false);
2551  }
2552  try
2553  {
2554  root.InnerInvokeWithArg(internalCurrent);
2555  }
2556  catch (Exception ex)
2557  {
2558  root.HandleException(ex);
2559  if (ex is ThreadAbortException)
2560  {
2561  internalCurrent.FinishThreadAbortedTask(bTAEAddedToExceptionHolder: false, delegateRan: true);
2562  }
2563  }
2564  object savedStateForNextReplica = internalCurrent.SavedStateForNextReplica;
2565  if (savedStateForNextReplica != null)
2566  {
2567  Task task2 = root.CreateReplicaTask(taskReplicaDelegate, root.m_stateObject, root, root.ExecutingTaskScheduler, creationOptionsForReplicas, internalOptionsForReplicas);
2568  ExecutionContext capturedContext2 = root.CapturedContext;
2569  task2.CapturedContext = CopyExecutionContext(capturedContext2);
2570  task2.HandedOverChildReplica = task;
2571  task2.SavedStateFromPreviousReplica = savedStateForNextReplica;
2572  task2.ScheduleAndStart(needsProtection: false);
2573  }
2574  else
2575  {
2576  replicasAreQuitting = true;
2577  try
2578  {
2579  task.InternalCancel(bCancelNonExecutingOnly: true);
2580  }
2581  catch (Exception unhandledException)
2582  {
2583  root.HandleException(unhandledException);
2584  }
2585  }
2586  };
2587  taskReplicaDelegate(null);
2588  }
2589 
2590  [SecurityCritical]
2591  void IThreadPoolWorkItem.ExecuteWorkItem()
2592  {
2593  ExecuteEntry(bPreventDoubleExecution: false);
2594  }
2595 
2596  [SecurityCritical]
2597  void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae)
2598  {
2599  if (!IsCompleted)
2600  {
2601  HandleException(tae);
2602  FinishThreadAbortedTask(bTAEAddedToExceptionHolder: true, delegateRan: false);
2603  }
2604  }
2605 
2606  [SecuritySafeCritical]
2607  internal bool ExecuteEntry(bool bPreventDoubleExecution)
2608  {
2609  if (bPreventDoubleExecution || (Options & (TaskCreationOptions)2048) != 0)
2610  {
2611  int oldFlags = 0;
2612  if (!AtomicStateUpdate(131072, 23199744, ref oldFlags) && (oldFlags & 0x400000) == 0)
2613  {
2614  return false;
2615  }
2616  }
2617  else
2618  {
2619  m_stateFlags |= 131072;
2620  }
2621  if (!IsCancellationRequested && !IsCanceled)
2622  {
2623  ExecuteWithThreadLocal(ref t_currentTask);
2624  }
2625  else if (!IsCanceled)
2626  {
2627  int num = Interlocked.Exchange(ref m_stateFlags, m_stateFlags | 0x400000);
2628  if ((num & 0x400000) == 0)
2629  {
2630  CancellationCleanupLogic();
2631  }
2632  }
2633  return true;
2634  }
2635 
2636  [SecurityCritical]
2637  private void ExecuteWithThreadLocal(ref Task currentTaskSlot)
2638  {
2639  Task task = currentTaskSlot;
2640  TplEtwProvider log = TplEtwProvider.Log;
2641  Guid oldActivityThatWillContinue = default(Guid);
2642  bool flag = log.IsEnabled();
2643  if (flag)
2644  {
2645  if (log.TasksSetActivityIds)
2646  {
2647  EventSource.SetCurrentThreadActivityId(TplEtwProvider.CreateGuidForTaskID(Id), out oldActivityThatWillContinue);
2648  }
2649  if (task != null)
2650  {
2651  log.TaskStarted(task.m_taskScheduler.Id, task.Id, Id);
2652  }
2653  else
2654  {
2655  log.TaskStarted(TaskScheduler.Current.Id, 0, Id);
2656  }
2657  }
2658  if (AsyncCausalityTracer.LoggingOn)
2659  {
2660  AsyncCausalityTracer.TraceSynchronousWorkStart(CausalityTraceLevel.Required, Id, CausalitySynchronousWork.Execution);
2661  }
2662  try
2663  {
2664  currentTaskSlot = this;
2665  ExecutionContext capturedContext = CapturedContext;
2666  if (capturedContext == null)
2667  {
2668  Execute();
2669  }
2670  else
2671  {
2672  if (IsSelfReplicatingRoot || IsChildReplica)
2673  {
2674  CapturedContext = CopyExecutionContext(capturedContext);
2675  }
2676  ContextCallback callback = ExecutionContextCallback;
2677  ExecutionContext.Run(capturedContext, callback, this, preserveSyncCtx: true);
2678  }
2679  if (AsyncCausalityTracer.LoggingOn)
2680  {
2681  AsyncCausalityTracer.TraceSynchronousWorkCompletion(CausalityTraceLevel.Required, CausalitySynchronousWork.Execution);
2682  }
2683  Finish(bUserDelegateExecuted: true);
2684  }
2685  finally
2686  {
2687  currentTaskSlot = task;
2688  if (flag)
2689  {
2690  if (task != null)
2691  {
2692  log.TaskCompleted(task.m_taskScheduler.Id, task.Id, Id, IsFaulted);
2693  }
2694  else
2695  {
2696  log.TaskCompleted(TaskScheduler.Current.Id, 0, Id, IsFaulted);
2697  }
2698  if (log.TasksSetActivityIds)
2699  {
2700  EventSource.SetCurrentThreadActivityId(oldActivityThatWillContinue);
2701  }
2702  }
2703  }
2704  }
2705 
2706  [SecurityCritical]
2707  private static void ExecutionContextCallback(object obj)
2708  {
2709  Task task = obj as Task;
2710  task.Execute();
2711  }
2712 
2713  internal virtual void InnerInvoke()
2714  {
2715  Action action = m_action as Action;
2716  if (action != null)
2717  {
2718  action();
2719  }
2720  else
2721  {
2722  (m_action as Action<object>)?.Invoke(m_stateObject);
2723  }
2724  }
2725 
2726  [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
2727  internal void InnerInvokeWithArg(Task childTask)
2728  {
2729  InnerInvoke();
2730  }
2731 
2732  private void HandleException(Exception unhandledException)
2733  {
2734  OperationCanceledException ex = unhandledException as OperationCanceledException;
2735  if (ex != null && IsCancellationRequested && m_contingentProperties.m_cancellationToken == ex.CancellationToken)
2736  {
2737  SetCancellationAcknowledged();
2738  AddException(ex, representsCancellation: true);
2739  }
2740  else
2741  {
2742  AddException(unhandledException);
2743  }
2744  }
2745 
2748  [__DynamicallyInvokable]
2750  {
2751  return new TaskAwaiter(this);
2752  }
2753 
2758  [__DynamicallyInvokable]
2759  public ConfiguredTaskAwaitable ConfigureAwait(bool continueOnCapturedContext)
2760  {
2761  return new ConfiguredTaskAwaitable(this, continueOnCapturedContext);
2762  }
2763 
2764  [SecurityCritical]
2765  internal void SetContinuationForAwait(Action continuationAction, bool continueOnCapturedContext, bool flowExecutionContext, ref StackCrawlMark stackMark)
2766  {
2767  TaskContinuation taskContinuation = null;
2768  if (continueOnCapturedContext)
2769  {
2770  SynchronizationContext currentNoFlow = SynchronizationContext.CurrentNoFlow;
2771  if (currentNoFlow != null && currentNoFlow.GetType() != typeof(SynchronizationContext))
2772  {
2773  taskContinuation = new SynchronizationContextAwaitTaskContinuation(currentNoFlow, continuationAction, flowExecutionContext, ref stackMark);
2774  }
2775  else
2776  {
2777  TaskScheduler internalCurrent = TaskScheduler.InternalCurrent;
2778  if (internalCurrent != null && internalCurrent != TaskScheduler.Default)
2779  {
2780  taskContinuation = new TaskSchedulerAwaitTaskContinuation(internalCurrent, continuationAction, flowExecutionContext, ref stackMark);
2781  }
2782  }
2783  }
2784  if (taskContinuation == null && flowExecutionContext)
2785  {
2786  taskContinuation = new AwaitTaskContinuation(continuationAction, flowExecutionContext: true, ref stackMark);
2787  }
2788  if (taskContinuation != null)
2789  {
2790  if (!AddTaskContinuation(taskContinuation, addBeforeOthers: false))
2791  {
2792  taskContinuation.Run(this, bCanInlineContinuationTask: false);
2793  }
2794  }
2795  else if (!AddTaskContinuation(continuationAction, addBeforeOthers: false))
2796  {
2797  AwaitTaskContinuation.UnsafeScheduleAction(continuationAction, this);
2798  }
2799  }
2800 
2803  [__DynamicallyInvokable]
2804  public static YieldAwaitable Yield()
2805  {
2806  return default(YieldAwaitable);
2807  }
2808 
2812  [__DynamicallyInvokable]
2813  public void Wait()
2814  {
2815  Wait(-1, default(CancellationToken));
2816  }
2817 
2827  [__DynamicallyInvokable]
2828  public bool Wait(TimeSpan timeout)
2829  {
2830  long num = (long)timeout.TotalMilliseconds;
2831  if (num < -1 || num > int.MaxValue)
2832  {
2833  throw new ArgumentOutOfRangeException("timeout");
2834  }
2835  return Wait((int)num, default(CancellationToken));
2836  }
2837 
2843  [__DynamicallyInvokable]
2844  public void Wait(CancellationToken cancellationToken)
2845  {
2846  Wait(-1, cancellationToken);
2847  }
2848 
2857  [__DynamicallyInvokable]
2858  public bool Wait(int millisecondsTimeout)
2859  {
2860  return Wait(millisecondsTimeout, default(CancellationToken));
2861  }
2862 
2873  [__DynamicallyInvokable]
2874  public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken)
2875  {
2876  if (millisecondsTimeout < -1)
2877  {
2878  throw new ArgumentOutOfRangeException("millisecondsTimeout");
2879  }
2880  if (!IsWaitNotificationEnabledOrNotRanToCompletion)
2881  {
2882  return true;
2883  }
2884  if (!InternalWait(millisecondsTimeout, cancellationToken))
2885  {
2886  return false;
2887  }
2888  if (IsWaitNotificationEnabledOrNotRanToCompletion)
2889  {
2890  NotifyDebuggerOfWaitCompletionIfNecessary();
2891  if (IsCanceled)
2892  {
2893  cancellationToken.ThrowIfCancellationRequested();
2894  }
2895  ThrowIfExceptional(includeTaskCanceledExceptions: true);
2896  }
2897  return true;
2898  }
2899 
2900  private bool WrappedTryRunInline()
2901  {
2902  if (m_taskScheduler == null)
2903  {
2904  return false;
2905  }
2906  try
2907  {
2908  return m_taskScheduler.TryRunInline(this, taskWasPreviouslyQueued: true);
2909  }
2910  catch (Exception ex)
2911  {
2912  if (!(ex is ThreadAbortException))
2913  {
2914  TaskSchedulerException ex2 = new TaskSchedulerException(ex);
2915  throw ex2;
2916  }
2917  throw;
2918  }
2919  }
2920 
2921  [MethodImpl(MethodImplOptions.NoOptimization)]
2922  internal bool InternalWait(int millisecondsTimeout, CancellationToken cancellationToken)
2923  {
2924  TplEtwProvider log = TplEtwProvider.Log;
2925  bool flag = log.IsEnabled();
2926  if (flag)
2927  {
2928  Task internalCurrent = InternalCurrent;
2929  log.TaskWaitBegin(internalCurrent?.m_taskScheduler.Id ?? TaskScheduler.Default.Id, internalCurrent?.Id ?? 0, Id, TplEtwProvider.TaskWaitBehavior.Synchronous, 0, Thread.GetDomainID());
2930  }
2931  bool flag2 = IsCompleted;
2932  if (!flag2)
2933  {
2935  flag2 = ((millisecondsTimeout == -1 && !cancellationToken.CanBeCanceled && WrappedTryRunInline() && IsCompleted) || SpinThenBlockingWait(millisecondsTimeout, cancellationToken));
2936  }
2937  if (flag)
2938  {
2939  Task internalCurrent2 = InternalCurrent;
2940  if (internalCurrent2 != null)
2941  {
2942  log.TaskWaitEnd(internalCurrent2.m_taskScheduler.Id, internalCurrent2.Id, Id);
2943  }
2944  else
2945  {
2946  log.TaskWaitEnd(TaskScheduler.Default.Id, 0, Id);
2947  }
2948  log.TaskWaitContinuationComplete(Id);
2949  }
2950  return flag2;
2951  }
2952 
2953  private bool SpinThenBlockingWait(int millisecondsTimeout, CancellationToken cancellationToken)
2954  {
2955  bool flag = millisecondsTimeout == -1;
2956  uint num = (uint)((!flag) ? Environment.TickCount : 0);
2957  bool flag2 = SpinWait(millisecondsTimeout);
2958  if (!flag2)
2959  {
2960  SetOnInvokeMres setOnInvokeMres = new SetOnInvokeMres();
2961  try
2962  {
2963  AddCompletionAction(setOnInvokeMres, addBeforeOthers: true);
2964  if (flag)
2965  {
2966  return setOnInvokeMres.Wait(-1, cancellationToken);
2967  }
2968  uint num2 = (uint)(Environment.TickCount - (int)num);
2969  if (num2 < millisecondsTimeout)
2970  {
2971  return setOnInvokeMres.Wait((int)(millisecondsTimeout - num2), cancellationToken);
2972  }
2973  return flag2;
2974  }
2975  finally
2976  {
2977  if (!IsCompleted)
2978  {
2979  RemoveContinuation(setOnInvokeMres);
2980  }
2981  }
2982  }
2983  return flag2;
2984  }
2985 
2986  private bool SpinWait(int millisecondsTimeout)
2987  {
2988  if (IsCompleted)
2989  {
2990  return true;
2991  }
2992  if (millisecondsTimeout == 0)
2993  {
2994  return false;
2995  }
2996  int num = PlatformHelper.IsSingleProcessor ? 1 : 10;
2997  for (int i = 0; i < num; i++)
2998  {
2999  if (IsCompleted)
3000  {
3001  return true;
3002  }
3003  if (i == num / 2)
3004  {
3005  Thread.Yield();
3006  }
3007  else
3008  {
3009  Thread.SpinWait(PlatformHelper.ProcessorCount * (4 << i));
3010  }
3011  }
3012  return IsCompleted;
3013  }
3014 
3015  [SecuritySafeCritical]
3016  internal bool InternalCancel(bool bCancelNonExecutingOnly)
3017  {
3018  bool flag = false;
3019  bool flag2 = false;
3020  TaskSchedulerException ex = null;
3021  if ((m_stateFlags & 0x10000) != 0)
3022  {
3023  TaskScheduler taskScheduler = m_taskScheduler;
3024  try
3025  {
3026  flag = (taskScheduler?.TryDequeue(this) ?? false);
3027  }
3028  catch (Exception ex2)
3029  {
3030  if (!(ex2 is ThreadAbortException))
3031  {
3032  ex = new TaskSchedulerException(ex2);
3033  }
3034  }
3035  bool flag3 = (taskScheduler != null && taskScheduler.RequiresAtomicStartTransition) || (Options & (TaskCreationOptions)2048) != TaskCreationOptions.None;
3036  if ((!flag && bCancelNonExecutingOnly) & flag3)
3037  {
3038  flag2 = AtomicStateUpdate(4194304, 4325376);
3039  }
3040  }
3041  if (!bCancelNonExecutingOnly | flag | flag2)
3042  {
3043  RecordInternalCancellationRequest();
3044  if (flag)
3045  {
3046  flag2 = AtomicStateUpdate(4194304, 4325376);
3047  }
3048  else if (!flag2 && (m_stateFlags & 0x10000) == 0)
3049  {
3050  flag2 = AtomicStateUpdate(4194304, 23265280);
3051  }
3052  if (flag2)
3053  {
3054  CancellationCleanupLogic();
3055  }
3056  }
3057  if (ex != null)
3058  {
3059  throw ex;
3060  }
3061  return flag2;
3062  }
3063 
3064  internal void RecordInternalCancellationRequest()
3065  {
3066  ContingentProperties contingentProperties = EnsureContingentPropertiesInitialized(needsProtection: true);
3067  contingentProperties.m_internalCancellationRequested = 1;
3068  }
3069 
3070  internal void RecordInternalCancellationRequest(CancellationToken tokenToRecord)
3071  {
3072  RecordInternalCancellationRequest();
3073  if (tokenToRecord != default(CancellationToken))
3074  {
3075  m_contingentProperties.m_cancellationToken = tokenToRecord;
3076  }
3077  }
3078 
3079  internal void RecordInternalCancellationRequest(CancellationToken tokenToRecord, object cancellationException)
3080  {
3081  RecordInternalCancellationRequest(tokenToRecord);
3082  if (cancellationException != null)
3083  {
3084  AddException(cancellationException, representsCancellation: true);
3085  }
3086  }
3087 
3088  internal void CancellationCleanupLogic()
3089  {
3090  Interlocked.Exchange(ref m_stateFlags, m_stateFlags | 0x400000);
3091  ContingentProperties contingentProperties = m_contingentProperties;
3092  if (contingentProperties != null)
3093  {
3094  contingentProperties.SetCompleted();
3095  contingentProperties.DeregisterCancellationCallback();
3096  }
3097  if (AsyncCausalityTracer.LoggingOn)
3098  {
3099  AsyncCausalityTracer.TraceOperationCompletion(CausalityTraceLevel.Required, Id, AsyncCausalityStatus.Canceled);
3100  }
3101  if (s_asyncDebuggingEnabled)
3102  {
3103  RemoveFromActiveTasks(Id);
3104  }
3105  FinishStageThree();
3106  }
3107 
3108  private void SetCancellationAcknowledged()
3109  {
3110  m_stateFlags |= 1048576;
3111  }
3112 
3113  [SecuritySafeCritical]
3114  internal void FinishContinuations()
3115  {
3116  object obj = Interlocked.Exchange(ref m_continuationObject, s_taskCompletionSentinel);
3117  TplEtwProvider.Log.RunningContinuation(Id, obj);
3118  if (obj == null)
3119  {
3120  return;
3121  }
3122  if (AsyncCausalityTracer.LoggingOn)
3123  {
3124  AsyncCausalityTracer.TraceSynchronousWorkStart(CausalityTraceLevel.Required, Id, CausalitySynchronousWork.CompletionNotification);
3125  }
3126  bool flag = (m_stateFlags & 0x8000000) == 0 && Thread.CurrentThread.ThreadState != ThreadState.AbortRequested && (m_stateFlags & 0x40) == 0;
3127  Action action = obj as Action;
3128  if (action != null)
3129  {
3130  AwaitTaskContinuation.RunOrScheduleAction(action, flag, ref t_currentTask);
3131  LogFinishCompletionNotification();
3132  return;
3133  }
3134  ITaskCompletionAction taskCompletionAction = obj as ITaskCompletionAction;
3135  if (taskCompletionAction != null)
3136  {
3137  if (flag)
3138  {
3139  taskCompletionAction.Invoke(this);
3140  }
3141  else
3142  {
3143  ThreadPool.UnsafeQueueCustomWorkItem(new CompletionActionInvoker(taskCompletionAction, this), forceGlobal: false);
3144  }
3145  LogFinishCompletionNotification();
3146  return;
3147  }
3148  TaskContinuation taskContinuation = obj as TaskContinuation;
3149  if (taskContinuation != null)
3150  {
3151  taskContinuation.Run(this, flag);
3152  LogFinishCompletionNotification();
3153  return;
3154  }
3155  List<object> list = obj as List<object>;
3156  if (list == null)
3157  {
3158  LogFinishCompletionNotification();
3159  return;
3160  }
3161  lock (list)
3162  {
3163  }
3164  int count = list.Count;
3165  for (int i = 0; i < count; i++)
3166  {
3167  StandardTaskContinuation standardTaskContinuation = list[i] as StandardTaskContinuation;
3168  if (standardTaskContinuation != null && (standardTaskContinuation.m_options & TaskContinuationOptions.ExecuteSynchronously) == TaskContinuationOptions.None)
3169  {
3170  TplEtwProvider.Log.RunningContinuationList(Id, i, standardTaskContinuation);
3171  list[i] = null;
3172  standardTaskContinuation.Run(this, flag);
3173  }
3174  }
3175  for (int j = 0; j < count; j++)
3176  {
3177  object obj2 = list[j];
3178  if (obj2 == null)
3179  {
3180  continue;
3181  }
3182  list[j] = null;
3183  TplEtwProvider.Log.RunningContinuationList(Id, j, obj2);
3184  Action action2 = obj2 as Action;
3185  if (action2 != null)
3186  {
3187  AwaitTaskContinuation.RunOrScheduleAction(action2, flag, ref t_currentTask);
3188  continue;
3189  }
3190  TaskContinuation taskContinuation2 = obj2 as TaskContinuation;
3191  if (taskContinuation2 != null)
3192  {
3193  taskContinuation2.Run(this, flag);
3194  continue;
3195  }
3196  ITaskCompletionAction taskCompletionAction2 = (ITaskCompletionAction)obj2;
3197  if (flag)
3198  {
3199  taskCompletionAction2.Invoke(this);
3200  }
3201  else
3202  {
3203  ThreadPool.UnsafeQueueCustomWorkItem(new CompletionActionInvoker(taskCompletionAction2, this), forceGlobal: false);
3204  }
3205  }
3206  LogFinishCompletionNotification();
3207  }
3208 
3209  private void LogFinishCompletionNotification()
3210  {
3211  if (AsyncCausalityTracer.LoggingOn)
3212  {
3213  AsyncCausalityTracer.TraceSynchronousWorkCompletion(CausalityTraceLevel.Required, CausalitySynchronousWork.CompletionNotification);
3214  }
3215  }
3216 
3221  [MethodImpl(MethodImplOptions.NoInlining)]
3222  [__DynamicallyInvokable]
3223  public Task ContinueWith(Action<Task> continuationAction)
3224  {
3225  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
3226  return ContinueWith(continuationAction, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
3227  }
3228 
3235  [MethodImpl(MethodImplOptions.NoInlining)]
3236  [__DynamicallyInvokable]
3237  public Task ContinueWith(Action<Task> continuationAction, CancellationToken cancellationToken)
3238  {
3239  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
3240  return ContinueWith(continuationAction, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None, ref stackMark);
3241  }
3242 
3249  [MethodImpl(MethodImplOptions.NoInlining)]
3250  [__DynamicallyInvokable]
3251  public Task ContinueWith(Action<Task> continuationAction, TaskScheduler scheduler)
3252  {
3253  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
3254  return ContinueWith(continuationAction, scheduler, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
3255  }
3256 
3263  [MethodImpl(MethodImplOptions.NoInlining)]
3264  [__DynamicallyInvokable]
3265  public Task ContinueWith(Action<Task> continuationAction, TaskContinuationOptions continuationOptions)
3266  {
3267  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
3268  return ContinueWith(continuationAction, TaskScheduler.Current, default(CancellationToken), continuationOptions, ref stackMark);
3269  }
3270 
3280  [MethodImpl(MethodImplOptions.NoInlining)]
3281  [__DynamicallyInvokable]
3282  public Task ContinueWith(Action<Task> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
3283  {
3284  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
3285  return ContinueWith(continuationAction, scheduler, cancellationToken, continuationOptions, ref stackMark);
3286  }
3287 
3288  private Task ContinueWith(Action<Task> continuationAction, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, ref StackCrawlMark stackMark)
3289  {
3290  if (continuationAction == null)
3291  {
3292  throw new ArgumentNullException("continuationAction");
3293  }
3294  if (scheduler == null)
3295  {
3296  throw new ArgumentNullException("scheduler");
3297  }
3298  CreationOptionsFromContinuationOptions(continuationOptions, out TaskCreationOptions creationOptions, out InternalTaskOptions internalOptions);
3299  Task task = new ContinuationTaskFromTask(this, continuationAction, null, creationOptions, internalOptions, ref stackMark);
3300  ContinueWithCore(task, scheduler, cancellationToken, continuationOptions);
3301  return task;
3302  }
3303 
3309  [MethodImpl(MethodImplOptions.NoInlining)]
3310  [__DynamicallyInvokable]
3311  public Task ContinueWith(Action<Task, object> continuationAction, object state)
3312  {
3313  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
3314  return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
3315  }
3316 
3324  [MethodImpl(MethodImplOptions.NoInlining)]
3325  [__DynamicallyInvokable]
3326  public Task ContinueWith(Action<Task, object> continuationAction, object state, CancellationToken cancellationToken)
3327  {
3328  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
3329  return ContinueWith(continuationAction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None, ref stackMark);
3330  }
3331 
3339  [MethodImpl(MethodImplOptions.NoInlining)]
3340  [__DynamicallyInvokable]
3341  public Task ContinueWith(Action<Task, object> continuationAction, object state, TaskScheduler scheduler)
3342  {
3343  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
3344  return ContinueWith(continuationAction, state, scheduler, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
3345  }
3346 
3354  [MethodImpl(MethodImplOptions.NoInlining)]
3355  [__DynamicallyInvokable]
3356  public Task ContinueWith(Action<Task, object> continuationAction, object state, TaskContinuationOptions continuationOptions)
3357  {
3358  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
3359  return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions, ref stackMark);
3360  }
3361 
3373  [MethodImpl(MethodImplOptions.NoInlining)]
3374  [__DynamicallyInvokable]
3375  public Task ContinueWith(Action<Task, object> continuationAction, object state, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
3376  {
3377  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
3378  return ContinueWith(continuationAction, state, scheduler, cancellationToken, continuationOptions, ref stackMark);
3379  }
3380 
3381  private Task ContinueWith(Action<Task, object> continuationAction, object state, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, ref StackCrawlMark stackMark)
3382  {
3383  if (continuationAction == null)
3384  {
3385  throw new ArgumentNullException("continuationAction");
3386  }
3387  if (scheduler == null)
3388  {
3389  throw new ArgumentNullException("scheduler");
3390  }
3391  CreationOptionsFromContinuationOptions(continuationOptions, out TaskCreationOptions creationOptions, out InternalTaskOptions internalOptions);
3392  Task task = new ContinuationTaskFromTask(this, continuationAction, state, creationOptions, internalOptions, ref stackMark);
3393  ContinueWithCore(task, scheduler, cancellationToken, continuationOptions);
3394  return task;
3395  }
3396 
3403  [MethodImpl(MethodImplOptions.NoInlining)]
3404  [__DynamicallyInvokable]
3405  public Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction)
3406  {
3407  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
3408  return ContinueWith(continuationFunction, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
3409  }
3410 
3418  [MethodImpl(MethodImplOptions.NoInlining)]
3419  [__DynamicallyInvokable]
3420  public Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction, CancellationToken cancellationToken)
3421  {
3422  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
3423  return ContinueWith(continuationFunction, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None, ref stackMark);
3424  }
3425 
3433  [MethodImpl(MethodImplOptions.NoInlining)]
3434  [__DynamicallyInvokable]
3435  public Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction, TaskScheduler scheduler)
3436  {
3437  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
3438  return ContinueWith(continuationFunction, scheduler, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
3439  }
3440 
3449  [MethodImpl(MethodImplOptions.NoInlining)]
3450  [__DynamicallyInvokable]
3451  public Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction, TaskContinuationOptions continuationOptions)
3452  {
3453  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
3454  return ContinueWith(continuationFunction, TaskScheduler.Current, default(CancellationToken), continuationOptions, ref stackMark);
3455  }
3456 
3467  [MethodImpl(MethodImplOptions.NoInlining)]
3468  [__DynamicallyInvokable]
3469  public Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
3470  {
3471  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
3472  return ContinueWith(continuationFunction, scheduler, cancellationToken, continuationOptions, ref stackMark);
3473  }
3474 
3475  private Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, ref StackCrawlMark stackMark)
3476  {
3477  if (continuationFunction == null)
3478  {
3479  throw new ArgumentNullException("continuationFunction");
3480  }
3481  if (scheduler == null)
3482  {
3483  throw new ArgumentNullException("scheduler");
3484  }
3485  CreationOptionsFromContinuationOptions(continuationOptions, out TaskCreationOptions creationOptions, out InternalTaskOptions internalOptions);
3486  Task<TResult> task = new ContinuationResultTaskFromTask<TResult>(this, continuationFunction, null, creationOptions, internalOptions, ref stackMark);
3487  ContinueWithCore(task, scheduler, cancellationToken, continuationOptions);
3488  return task;
3489  }
3490 
3497  [MethodImpl(MethodImplOptions.NoInlining)]
3498  [__DynamicallyInvokable]
3499  public Task<TResult> ContinueWith<TResult>(Func<Task, object, TResult> continuationFunction, object state)
3500  {
3501  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
3502  return ContinueWith(continuationFunction, state, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
3503  }
3504 
3513  [MethodImpl(MethodImplOptions.NoInlining)]
3514  [__DynamicallyInvokable]
3515  public Task<TResult> ContinueWith<TResult>(Func<Task, object, TResult> continuationFunction, object state, CancellationToken cancellationToken)
3516  {
3517  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
3518  return ContinueWith(continuationFunction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None, ref stackMark);
3519  }
3520 
3529  [MethodImpl(MethodImplOptions.NoInlining)]
3530  [__DynamicallyInvokable]
3531  public Task<TResult> ContinueWith<TResult>(Func<Task, object, TResult> continuationFunction, object state, TaskScheduler scheduler)
3532  {
3533  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
3534  return ContinueWith(continuationFunction, state, scheduler, default(CancellationToken), TaskContinuationOptions.None, ref stackMark);
3535  }
3536 
3545  [MethodImpl(MethodImplOptions.NoInlining)]
3546  [__DynamicallyInvokable]
3547  public Task<TResult> ContinueWith<TResult>(Func<Task, object, TResult> continuationFunction, object state, TaskContinuationOptions continuationOptions)
3548  {
3549  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
3550  return ContinueWith(continuationFunction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions, ref stackMark);
3551  }
3552 
3565  [MethodImpl(MethodImplOptions.NoInlining)]
3566  [__DynamicallyInvokable]
3567  public Task<TResult> ContinueWith<TResult>(Func<Task, object, TResult> continuationFunction, object state, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
3568  {
3569  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
3570  return ContinueWith(continuationFunction, state, scheduler, cancellationToken, continuationOptions, ref stackMark);
3571  }
3572 
3573  private Task<TResult> ContinueWith<TResult>(Func<Task, object, TResult> continuationFunction, object state, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, ref StackCrawlMark stackMark)
3574  {
3575  if (continuationFunction == null)
3576  {
3577  throw new ArgumentNullException("continuationFunction");
3578  }
3579  if (scheduler == null)
3580  {
3581  throw new ArgumentNullException("scheduler");
3582  }
3583  CreationOptionsFromContinuationOptions(continuationOptions, out TaskCreationOptions creationOptions, out InternalTaskOptions internalOptions);
3584  Task<TResult> task = new ContinuationResultTaskFromTask<TResult>(this, continuationFunction, state, creationOptions, internalOptions, ref stackMark);
3585  ContinueWithCore(task, scheduler, cancellationToken, continuationOptions);
3586  return task;
3587  }
3588 
3589  internal static void CreationOptionsFromContinuationOptions(TaskContinuationOptions continuationOptions, out TaskCreationOptions creationOptions, out InternalTaskOptions internalOptions)
3590  {
3591  TaskContinuationOptions taskContinuationOptions = TaskContinuationOptions.NotOnRanToCompletion | TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.NotOnCanceled;
3592  TaskContinuationOptions taskContinuationOptions2 = TaskContinuationOptions.PreferFairness | TaskContinuationOptions.LongRunning | TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.DenyChildAttach | TaskContinuationOptions.HideScheduler | TaskContinuationOptions.RunContinuationsAsynchronously;
3593  TaskContinuationOptions taskContinuationOptions3 = TaskContinuationOptions.LongRunning | TaskContinuationOptions.ExecuteSynchronously;
3594  if ((continuationOptions & taskContinuationOptions3) == taskContinuationOptions3)
3595  {
3596  throw new ArgumentOutOfRangeException("continuationOptions", Environment.GetResourceString("Task_ContinueWith_ESandLR"));
3597  }
3598  if ((continuationOptions & ~(taskContinuationOptions2 | taskContinuationOptions | TaskContinuationOptions.LazyCancellation | TaskContinuationOptions.ExecuteSynchronously)) != 0)
3599  {
3600  throw new ArgumentOutOfRangeException("continuationOptions");
3601  }
3602  if ((continuationOptions & taskContinuationOptions) == taskContinuationOptions)
3603  {
3604  throw new ArgumentOutOfRangeException("continuationOptions", Environment.GetResourceString("Task_ContinueWith_NotOnAnything"));
3605  }
3606  creationOptions = (TaskCreationOptions)(continuationOptions & taskContinuationOptions2);
3607  internalOptions = InternalTaskOptions.ContinuationTask;
3608  if ((continuationOptions & TaskContinuationOptions.LazyCancellation) != 0)
3609  {
3610  internalOptions |= InternalTaskOptions.LazyCancellation;
3611  }
3612  }
3613 
3614  internal void ContinueWithCore(Task continuationTask, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions options)
3615  {
3616  TaskContinuation taskContinuation = new StandardTaskContinuation(continuationTask, options, scheduler);
3617  if (cancellationToken.CanBeCanceled)
3618  {
3619  if (IsCompleted || cancellationToken.IsCancellationRequested)
3620  {
3621  continuationTask.AssignCancellationToken(cancellationToken, null, null);
3622  }
3623  else
3624  {
3625  continuationTask.AssignCancellationToken(cancellationToken, this, taskContinuation);
3626  }
3627  }
3628  if (continuationTask.IsCompleted)
3629  {
3630  return;
3631  }
3632  if ((Options & (TaskCreationOptions)1024) != 0 && !(this is ITaskCompletionAction))
3633  {
3634  TplEtwProvider log = TplEtwProvider.Log;
3635  if (log.IsEnabled())
3636  {
3637  log.AwaitTaskContinuationScheduled(TaskScheduler.Current.Id, CurrentId ?? 0, continuationTask.Id);
3638  }
3639  }
3640  if (!AddTaskContinuation(taskContinuation, addBeforeOthers: false))
3641  {
3642  taskContinuation.Run(this, bCanInlineContinuationTask: true);
3643  }
3644  }
3645 
3646  internal void AddCompletionAction(ITaskCompletionAction action)
3647  {
3648  AddCompletionAction(action, addBeforeOthers: false);
3649  }
3650 
3651  private void AddCompletionAction(ITaskCompletionAction action, bool addBeforeOthers)
3652  {
3653  if (!AddTaskContinuation(action, addBeforeOthers))
3654  {
3655  action.Invoke(this);
3656  }
3657  }
3658 
3659  private bool AddTaskContinuationComplex(object tc, bool addBeforeOthers)
3660  {
3661  object continuationObject = m_continuationObject;
3662  if (continuationObject != s_taskCompletionSentinel && !(continuationObject is List<object>))
3663  {
3664  List<object> list = new List<object>();
3665  list.Add(continuationObject);
3666  Interlocked.CompareExchange(ref m_continuationObject, list, continuationObject);
3667  }
3668  List<object> list2 = m_continuationObject as List<object>;
3669  if (list2 != null)
3670  {
3671  lock (list2)
3672  {
3673  if (m_continuationObject != s_taskCompletionSentinel)
3674  {
3675  if (list2.Count == list2.Capacity)
3676  {
3677  list2.RemoveAll(s_IsTaskContinuationNullPredicate);
3678  }
3679  if (addBeforeOthers)
3680  {
3681  list2.Insert(0, tc);
3682  }
3683  else
3684  {
3685  list2.Add(tc);
3686  }
3687  return true;
3688  }
3689  }
3690  }
3691  return false;
3692  }
3693 
3694  private bool AddTaskContinuation(object tc, bool addBeforeOthers)
3695  {
3696  if (IsCompleted)
3697  {
3698  return false;
3699  }
3700  if (m_continuationObject != null || Interlocked.CompareExchange(ref m_continuationObject, tc, null) != null)
3701  {
3702  return AddTaskContinuationComplex(tc, addBeforeOthers);
3703  }
3704  return true;
3705  }
3706 
3707  internal void RemoveContinuation(object continuationObject)
3708  {
3709  object continuationObject2 = m_continuationObject;
3710  if (continuationObject2 == s_taskCompletionSentinel)
3711  {
3712  return;
3713  }
3714  List<object> list = continuationObject2 as List<object>;
3715  if (list == null)
3716  {
3717  if (Interlocked.CompareExchange(ref m_continuationObject, new List<object>(), continuationObject) == continuationObject)
3718  {
3719  return;
3720  }
3721  list = (m_continuationObject as List<object>);
3722  }
3723  if (list != null)
3724  {
3725  lock (list)
3726  {
3727  if (m_continuationObject != s_taskCompletionSentinel)
3728  {
3729  int num = list.IndexOf(continuationObject);
3730  if (num != -1)
3731  {
3732  list[num] = null;
3733  }
3734  }
3735  }
3736  }
3737  }
3738 
3745  [MethodImpl(MethodImplOptions.NoOptimization)]
3746  [__DynamicallyInvokable]
3747  public static void WaitAll(params Task[] tasks)
3748  {
3749  WaitAll(tasks, -1);
3750  }
3751 
3764  [MethodImpl(MethodImplOptions.NoOptimization)]
3765  [__DynamicallyInvokable]
3766  public static bool WaitAll(Task[] tasks, TimeSpan timeout)
3767  {
3768  long num = (long)timeout.TotalMilliseconds;
3769  if (num < -1 || num > int.MaxValue)
3770  {
3771  throw new ArgumentOutOfRangeException("timeout");
3772  }
3773  return WaitAll(tasks, (int)num);
3774  }
3775 
3787  [MethodImpl(MethodImplOptions.NoOptimization)]
3788  [__DynamicallyInvokable]
3789  public static bool WaitAll(Task[] tasks, int millisecondsTimeout)
3790  {
3791  return WaitAll(tasks, millisecondsTimeout, default(CancellationToken));
3792  }
3793 
3802  [MethodImpl(MethodImplOptions.NoOptimization)]
3803  [__DynamicallyInvokable]
3804  public static void WaitAll(Task[] tasks, CancellationToken cancellationToken)
3805  {
3806  WaitAll(tasks, -1, cancellationToken);
3807  }
3808 
3822  [MethodImpl(MethodImplOptions.NoOptimization)]
3823  [__DynamicallyInvokable]
3824  public static bool WaitAll(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
3825  {
3826  if (tasks == null)
3827  {
3828  throw new ArgumentNullException("tasks");
3829  }
3830  if (millisecondsTimeout < -1)
3831  {
3832  throw new ArgumentOutOfRangeException("millisecondsTimeout");
3833  }
3834  cancellationToken.ThrowIfCancellationRequested();
3835  List<Exception> exceptions = null;
3836  List<Task> list = null;
3837  List<Task> list2 = null;
3838  bool flag = false;
3839  bool flag2 = false;
3840  bool flag3 = true;
3841  for (int num = tasks.Length - 1; num >= 0; num--)
3842  {
3843  Task task = tasks[num];
3844  if (task == null)
3845  {
3846  throw new ArgumentException(Environment.GetResourceString("Task_WaitMulti_NullTask"), "tasks");
3847  }
3848  bool flag4 = task.IsCompleted;
3849  if (!flag4)
3850  {
3851  if (millisecondsTimeout != -1 || cancellationToken.CanBeCanceled)
3852  {
3853  AddToList(task, ref list, tasks.Length);
3854  }
3855  else
3856  {
3857  flag4 = (task.WrappedTryRunInline() && task.IsCompleted);
3858  if (!flag4)
3859  {
3860  AddToList(task, ref list, tasks.Length);
3861  }
3862  }
3863  }
3864  if (flag4)
3865  {
3866  if (task.IsFaulted)
3867  {
3868  flag = true;
3869  }
3870  else if (task.IsCanceled)
3871  {
3872  flag2 = true;
3873  }
3874  if (task.IsWaitNotificationEnabled)
3875  {
3876  AddToList(task, ref list2, 1);
3877  }
3878  }
3879  }
3880  if (list != null)
3881  {
3882  flag3 = WaitAllBlockingCore(list, millisecondsTimeout, cancellationToken);
3883  if (flag3)
3884  {
3885  foreach (Task item in list)
3886  {
3887  if (item.IsFaulted)
3888  {
3889  flag = true;
3890  }
3891  else if (item.IsCanceled)
3892  {
3893  flag2 = true;
3894  }
3895  if (item.IsWaitNotificationEnabled)
3896  {
3897  AddToList(item, ref list2, 1);
3898  }
3899  }
3900  }
3901  GC.KeepAlive(tasks);
3902  }
3903  if (flag3 && list2 != null)
3904  {
3905  foreach (Task item2 in list2)
3906  {
3907  if (item2.NotifyDebuggerOfWaitCompletionIfNecessary())
3908  {
3909  break;
3910  }
3911  }
3912  }
3913  if (flag3 && (flag | flag2))
3914  {
3915  if (!flag)
3916  {
3917  cancellationToken.ThrowIfCancellationRequested();
3918  }
3919  foreach (Task t in tasks)
3920  {
3921  AddExceptionsForCompletedTask(ref exceptions, t);
3922  }
3923  throw new AggregateException(exceptions);
3924  }
3925  return flag3;
3926  }
3927 
3928  private static void AddToList<T>(T item, ref List<T> list, int initSize)
3929  {
3930  if (list == null)
3931  {
3932  list = new List<T>(initSize);
3933  }
3934  list.Add(item);
3935  }
3936 
3937  private static bool WaitAllBlockingCore(List<Task> tasks, int millisecondsTimeout, CancellationToken cancellationToken)
3938  {
3939  bool flag = false;
3940  SetOnCountdownMres setOnCountdownMres = new SetOnCountdownMres(tasks.Count);
3941  try
3942  {
3943  foreach (Task task in tasks)
3944  {
3945  task.AddCompletionAction(setOnCountdownMres, addBeforeOthers: true);
3946  }
3947  flag = setOnCountdownMres.Wait(millisecondsTimeout, cancellationToken);
3948  return flag;
3949  }
3950  finally
3951  {
3952  if (!flag)
3953  {
3954  foreach (Task task2 in tasks)
3955  {
3956  if (!task2.IsCompleted)
3957  {
3958  task2.RemoveContinuation(setOnCountdownMres);
3959  }
3960  }
3961  }
3962  }
3963  }
3964 
3965  internal static void FastWaitAll(Task[] tasks)
3966  {
3967  List<Exception> exceptions = null;
3968  for (int num = tasks.Length - 1; num >= 0; num--)
3969  {
3970  if (!tasks[num].IsCompleted)
3971  {
3972  tasks[num].WrappedTryRunInline();
3973  }
3974  }
3975  for (int num2 = tasks.Length - 1; num2 >= 0; num2--)
3976  {
3977  Task task = tasks[num2];
3978  task.SpinThenBlockingWait(-1, default(CancellationToken));
3979  AddExceptionsForCompletedTask(ref exceptions, task);
3980  }
3981  if (exceptions != null)
3982  {
3983  throw new AggregateException(exceptions);
3984  }
3985  }
3986 
3987  internal static void AddExceptionsForCompletedTask(ref List<Exception> exceptions, Task t)
3988  {
3989  AggregateException exceptions2 = t.GetExceptions(includeTaskCanceledExceptions: true);
3990  if (exceptions2 != null)
3991  {
3992  t.UpdateExceptionObservedStatus();
3993  if (exceptions == null)
3994  {
3995  exceptions = new List<Exception>(exceptions2.InnerExceptions.Count);
3996  }
3997  exceptions.AddRange(exceptions2.InnerExceptions);
3998  }
3999  }
4000 
4007  [MethodImpl(MethodImplOptions.NoOptimization)]
4008  [__DynamicallyInvokable]
4009  public static int WaitAny(params Task[] tasks)
4010  {
4011  return WaitAny(tasks, -1);
4012  }
4013 
4024  [MethodImpl(MethodImplOptions.NoOptimization)]
4025  [__DynamicallyInvokable]
4026  public static int WaitAny(Task[] tasks, TimeSpan timeout)
4027  {
4028  long num = (long)timeout.TotalMilliseconds;
4029  if (num < -1 || num > int.MaxValue)
4030  {
4031  throw new ArgumentOutOfRangeException("timeout");
4032  }
4033  return WaitAny(tasks, (int)num);
4034  }
4035 
4044  [MethodImpl(MethodImplOptions.NoOptimization)]
4045  [__DynamicallyInvokable]
4046  public static int WaitAny(Task[] tasks, CancellationToken cancellationToken)
4047  {
4048  return WaitAny(tasks, -1, cancellationToken);
4049  }
4050 
4060  [MethodImpl(MethodImplOptions.NoOptimization)]
4061  [__DynamicallyInvokable]
4062  public static int WaitAny(Task[] tasks, int millisecondsTimeout)
4063  {
4064  return WaitAny(tasks, millisecondsTimeout, default(CancellationToken));
4065  }
4066 
4078  [MethodImpl(MethodImplOptions.NoOptimization)]
4079  [__DynamicallyInvokable]
4080  public static int WaitAny(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
4081  {
4082  if (tasks == null)
4083  {
4084  throw new ArgumentNullException("tasks");
4085  }
4086  if (millisecondsTimeout < -1)
4087  {
4088  throw new ArgumentOutOfRangeException("millisecondsTimeout");
4089  }
4090  cancellationToken.ThrowIfCancellationRequested();
4091  int num = -1;
4092  for (int i = 0; i < tasks.Length; i++)
4093  {
4094  Task task = tasks[i];
4095  if (task == null)
4096  {
4097  throw new ArgumentException(Environment.GetResourceString("Task_WaitMulti_NullTask"), "tasks");
4098  }
4099  if (num == -1 && task.IsCompleted)
4100  {
4101  num = i;
4102  }
4103  }
4104  if (num == -1 && tasks.Length != 0)
4105  {
4106  Task<Task> task2 = TaskFactory.CommonCWAnyLogic(tasks);
4107  if (task2.Wait(millisecondsTimeout, cancellationToken))
4108  {
4109  num = Array.IndexOf(tasks, task2.Result);
4110  }
4111  }
4112  GC.KeepAlive(tasks);
4113  return num;
4114  }
4115 
4120  [__DynamicallyInvokable]
4121  public static Task<TResult> FromResult<TResult>(TResult result)
4122  {
4123  return new Task<TResult>(result);
4124  }
4125 
4129  [__DynamicallyInvokable]
4130  public static Task FromException(Exception exception)
4131  {
4132  return FromException<VoidTaskResult>(exception);
4133  }
4134 
4139  [__DynamicallyInvokable]
4141  {
4142  if (exception == null)
4143  {
4144  throw new ArgumentNullException("exception");
4145  }
4146  Task<TResult> task = new Task<TResult>();
4147  bool flag = task.TrySetException(exception);
4148  return task;
4149  }
4150 
4151  [FriendAccessAllowed]
4152  internal static Task FromCancellation(CancellationToken cancellationToken)
4153  {
4154  if (!cancellationToken.IsCancellationRequested)
4155  {
4156  throw new ArgumentOutOfRangeException("cancellationToken");
4157  }
4158  return new Task(canceled: true, TaskCreationOptions.None, cancellationToken);
4159  }
4160 
4165  [__DynamicallyInvokable]
4166  public static Task FromCanceled(CancellationToken cancellationToken)
4167  {
4168  return FromCancellation(cancellationToken);
4169  }
4170 
4171  [FriendAccessAllowed]
4172  internal static Task<TResult> FromCancellation<TResult>(CancellationToken cancellationToken)
4173  {
4174  if (!cancellationToken.IsCancellationRequested)
4175  {
4176  throw new ArgumentOutOfRangeException("cancellationToken");
4177  }
4178  return new Task<TResult>(canceled: true, default(TResult), TaskCreationOptions.None, cancellationToken);
4179  }
4180 
4186  [__DynamicallyInvokable]
4187  public static Task<TResult> FromCanceled<TResult>(CancellationToken cancellationToken)
4188  {
4189  return FromCancellation<TResult>(cancellationToken);
4190  }
4191 
4192  internal static Task<TResult> FromCancellation<TResult>(OperationCanceledException exception)
4193  {
4194  if (exception == null)
4195  {
4196  throw new ArgumentNullException("exception");
4197  }
4198  Task<TResult> task = new Task<TResult>();
4199  bool flag = task.TrySetCanceled(exception.CancellationToken, exception);
4200  return task;
4201  }
4202 
4207  [MethodImpl(MethodImplOptions.NoInlining)]
4208  [__DynamicallyInvokable]
4209  public static Task Run(Action action)
4210  {
4211  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
4212  return InternalStartNew(null, action, null, default(CancellationToken), TaskScheduler.Default, TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, ref stackMark);
4213  }
4214 
4222  [MethodImpl(MethodImplOptions.NoInlining)]
4223  [__DynamicallyInvokable]
4224  public static Task Run(Action action, CancellationToken cancellationToken)
4225  {
4226  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
4227  return InternalStartNew(null, action, null, cancellationToken, TaskScheduler.Default, TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, ref stackMark);
4228  }
4229 
4235  [MethodImpl(MethodImplOptions.NoInlining)]
4236  [__DynamicallyInvokable]
4237  public static Task<TResult> Run<TResult>(Func<TResult> function)
4238  {
4239  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
4240  return Task<TResult>.StartNew(null, function, default(CancellationToken), TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, TaskScheduler.Default, ref stackMark);
4241  }
4242 
4251  [MethodImpl(MethodImplOptions.NoInlining)]
4252  [__DynamicallyInvokable]
4253  public static Task<TResult> Run<TResult>(Func<TResult> function, CancellationToken cancellationToken)
4254  {
4255  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
4256  return Task<TResult>.StartNew(null, function, cancellationToken, TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, TaskScheduler.Default, ref stackMark);
4257  }
4258 
4263  [__DynamicallyInvokable]
4264  public static Task Run(Func<Task> function)
4265  {
4266  return Run(function, default(CancellationToken));
4267  }
4268 
4276  [__DynamicallyInvokable]
4277  public static Task Run(Func<Task> function, CancellationToken cancellationToken)
4278  {
4279  if (function == null)
4280  {
4281  throw new ArgumentNullException("function");
4282  }
4283  if (AppContextSwitches.ThrowExceptionIfDisposedCancellationTokenSource)
4284  {
4285  cancellationToken.ThrowIfSourceDisposed();
4286  }
4287  if (cancellationToken.IsCancellationRequested)
4288  {
4289  return FromCancellation(cancellationToken);
4290  }
4291  Task<Task> outerTask = Task<Task>.Factory.StartNew(function, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
4292  return new UnwrapPromise<VoidTaskResult>(outerTask, lookForOce: true);
4293  }
4294 
4300  [__DynamicallyInvokable]
4301  public static Task<TResult> Run<TResult>(Func<Task<TResult>> function)
4302  {
4303  return Run(function, default(CancellationToken));
4304  }
4305 
4314  [__DynamicallyInvokable]
4315  public static Task<TResult> Run<TResult>(Func<Task<TResult>> function, CancellationToken cancellationToken)
4316  {
4317  if (function == null)
4318  {
4319  throw new ArgumentNullException("function");
4320  }
4321  if (AppContextSwitches.ThrowExceptionIfDisposedCancellationTokenSource)
4322  {
4323  cancellationToken.ThrowIfSourceDisposed();
4324  }
4325  if (cancellationToken.IsCancellationRequested)
4326  {
4327  return FromCancellation<TResult>(cancellationToken);
4328  }
4329  Task<Task<TResult>> outerTask = Task<Task<TResult>>.Factory.StartNew(function, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
4330  return new UnwrapPromise<TResult>(outerTask, lookForOce: true);
4331  }
4332 
4338  [__DynamicallyInvokable]
4339  public static Task Delay(TimeSpan delay)
4340  {
4341  return Delay(delay, default(CancellationToken));
4342  }
4343 
4352  [__DynamicallyInvokable]
4353  public static Task Delay(TimeSpan delay, CancellationToken cancellationToken)
4354  {
4355  long num = (long)delay.TotalMilliseconds;
4356  if (num < -1 || num > int.MaxValue)
4357  {
4358  throw new ArgumentOutOfRangeException("delay", Environment.GetResourceString("Task_Delay_InvalidDelay"));
4359  }
4360  return Delay((int)num, cancellationToken);
4361  }
4362 
4367  [__DynamicallyInvokable]
4368  public static Task Delay(int millisecondsDelay)
4369  {
4370  return Delay(millisecondsDelay, default(CancellationToken));
4371  }
4372 
4380  [__DynamicallyInvokable]
4381  public static Task Delay(int millisecondsDelay, CancellationToken cancellationToken)
4382  {
4383  if (millisecondsDelay < -1)
4384  {
4385  throw new ArgumentOutOfRangeException("millisecondsDelay", Environment.GetResourceString("Task_Delay_InvalidMillisecondsDelay"));
4386  }
4387  if (cancellationToken.IsCancellationRequested)
4388  {
4389  return FromCancellation(cancellationToken);
4390  }
4391  if (millisecondsDelay == 0)
4392  {
4393  return CompletedTask;
4394  }
4395  DelayPromise delayPromise = new DelayPromise(cancellationToken);
4396  if (cancellationToken.CanBeCanceled)
4397  {
4398  delayPromise.Registration = cancellationToken.InternalRegisterWithoutEC(delegate(object state)
4399  {
4400  ((DelayPromise)state).Complete();
4401  }, delayPromise);
4402  }
4403  if (millisecondsDelay != -1)
4404  {
4405  delayPromise.Timer = new Timer(delegate(object state)
4406  {
4407  ((DelayPromise)state).Complete();
4408  }, delayPromise, millisecondsDelay, -1);
4409  delayPromise.Timer.KeepRootedWhileScheduled();
4410  }
4411  return delayPromise;
4412  }
4413 
4419  [__DynamicallyInvokable]
4420  public static Task WhenAll(IEnumerable<Task> tasks)
4421  {
4422  Task[] array = tasks as Task[];
4423  if (array != null)
4424  {
4425  return WhenAll(array);
4426  }
4427  ICollection<Task> collection = tasks as ICollection<Task>;
4428  if (collection != null)
4429  {
4430  int num = 0;
4431  array = new Task[collection.Count];
4432  foreach (Task task in tasks)
4433  {
4434  if (task == null)
4435  {
4436  throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), "tasks");
4437  }
4438  array[num++] = task;
4439  }
4440  return InternalWhenAll(array);
4441  }
4442  if (tasks == null)
4443  {
4444  throw new ArgumentNullException("tasks");
4445  }
4446  List<Task> list = new List<Task>();
4447  foreach (Task task2 in tasks)
4448  {
4449  if (task2 == null)
4450  {
4451  throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), "tasks");
4452  }
4453  list.Add(task2);
4454  }
4455  return InternalWhenAll(list.ToArray());
4456  }
4457 
4463  [__DynamicallyInvokable]
4464  public static Task WhenAll(params Task[] tasks)
4465  {
4466  if (tasks == null)
4467  {
4468  throw new ArgumentNullException("tasks");
4469  }
4470  int num = tasks.Length;
4471  if (num == 0)
4472  {
4473  return InternalWhenAll(tasks);
4474  }
4475  Task[] array = new Task[num];
4476  for (int i = 0; i < num; i++)
4477  {
4478  Task task = tasks[i];
4479  if (task == null)
4480  {
4481  throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), "tasks");
4482  }
4483  array[i] = task;
4484  }
4485  return InternalWhenAll(array);
4486  }
4487 
4488  private static Task InternalWhenAll(Task[] tasks)
4489  {
4490  if (tasks.Length != 0)
4491  {
4492  return new WhenAllPromise(tasks);
4493  }
4494  return CompletedTask;
4495  }
4496 
4503  [__DynamicallyInvokable]
4505  {
4506  Task<TResult>[] array = tasks as Task<TResult>[];
4507  if (array != null)
4508  {
4509  return WhenAll(array);
4510  }
4511  ICollection<Task<TResult>> collection = tasks as ICollection<Task<TResult>>;
4512  if (collection != null)
4513  {
4514  int num = 0;
4515  array = new Task<TResult>[collection.Count];
4516  foreach (Task<TResult> task in tasks)
4517  {
4518  if (task == null)
4519  {
4520  throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), "tasks");
4521  }
4522  array[num++] = task;
4523  }
4524  return InternalWhenAll(array);
4525  }
4526  if (tasks == null)
4527  {
4528  throw new ArgumentNullException("tasks");
4529  }
4530  List<Task<TResult>> list = new List<Task<TResult>>();
4531  foreach (Task<TResult> task2 in tasks)
4532  {
4533  if (task2 == null)
4534  {
4535  throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), "tasks");
4536  }
4537  list.Add(task2);
4538  }
4539  return InternalWhenAll(list.ToArray());
4540  }
4541 
4548  [__DynamicallyInvokable]
4549  public static Task<TResult[]> WhenAll<TResult>(params Task<TResult>[] tasks)
4550  {
4551  if (tasks == null)
4552  {
4553  throw new ArgumentNullException("tasks");
4554  }
4555  int num = tasks.Length;
4556  if (num == 0)
4557  {
4558  return InternalWhenAll(tasks);
4559  }
4560  Task<TResult>[] array = new Task<TResult>[num];
4561  for (int i = 0; i < num; i++)
4562  {
4563  Task<TResult> task = tasks[i];
4564  if (task == null)
4565  {
4566  throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), "tasks");
4567  }
4568  array[i] = task;
4569  }
4570  return InternalWhenAll(array);
4571  }
4572 
4573  private static Task<TResult[]> InternalWhenAll<TResult>(Task<TResult>[] tasks)
4574  {
4575  if (tasks.Length != 0)
4576  {
4577  return new WhenAllPromise<TResult>(tasks);
4578  }
4579  return new Task<TResult[]>(canceled: false, new TResult[0], TaskCreationOptions.None, default(CancellationToken));
4580  }
4581 
4587  [__DynamicallyInvokable]
4588  public static Task<Task> WhenAny(params Task[] tasks)
4589  {
4590  if (tasks == null)
4591  {
4592  throw new ArgumentNullException("tasks");
4593  }
4594  if (tasks.Length == 0)
4595  {
4596  throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_EmptyTaskList"), "tasks");
4597  }
4598  int num = tasks.Length;
4599  Task[] array = new Task[num];
4600  for (int i = 0; i < num; i++)
4601  {
4602  Task task = tasks[i];
4603  if (task == null)
4604  {
4605  throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), "tasks");
4606  }
4607  array[i] = task;
4608  }
4609  return TaskFactory.CommonCWAnyLogic(array);
4610  }
4611 
4617  [__DynamicallyInvokable]
4618  public static Task<Task> WhenAny(IEnumerable<Task> tasks)
4619  {
4620  if (tasks == null)
4621  {
4622  throw new ArgumentNullException("tasks");
4623  }
4624  List<Task> list = new List<Task>();
4625  foreach (Task task in tasks)
4626  {
4627  if (task == null)
4628  {
4629  throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), "tasks");
4630  }
4631  list.Add(task);
4632  }
4633  if (list.Count == 0)
4634  {
4635  throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_EmptyTaskList"), "tasks");
4636  }
4637  return TaskFactory.CommonCWAnyLogic(list);
4638  }
4639 
4646  [__DynamicallyInvokable]
4647  public static Task<Task<TResult>> WhenAny<TResult>(params Task<TResult>[] tasks)
4648  {
4649  Task<Task> task = WhenAny((Task[])tasks);
4650  return task.ContinueWith(Task<TResult>.TaskWhenAnyCast, default(CancellationToken), TaskContinuationOptions.DenyChildAttach | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
4651  }
4652 
4659  [__DynamicallyInvokable]
4661  {
4662  Task<Task> task = WhenAny((IEnumerable<Task>)tasks);
4663  return task.ContinueWith(Task<TResult>.TaskWhenAnyCast, default(CancellationToken), TaskContinuationOptions.DenyChildAttach | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
4664  }
4665 
4666  [FriendAccessAllowed]
4667  internal static Task<TResult> CreateUnwrapPromise<TResult>(Task outerTask, bool lookForOce)
4668  {
4669  return new UnwrapPromise<TResult>(outerTask, lookForOce);
4670  }
4671 
4672  internal virtual Delegate[] GetDelegateContinuationsForDebugger()
4673  {
4674  if (m_continuationObject != this)
4675  {
4676  return GetDelegatesFromContinuationObject(m_continuationObject);
4677  }
4678  return null;
4679  }
4680 
4681  internal static Delegate[] GetDelegatesFromContinuationObject(object continuationObject)
4682  {
4683  if (continuationObject != null)
4684  {
4685  Action action = continuationObject as Action;
4686  if (action != null)
4687  {
4688  return new Delegate[1]
4689  {
4690  AsyncMethodBuilderCore.TryGetStateMachineForDebugger(action)
4691  };
4692  }
4693  TaskContinuation taskContinuation = continuationObject as TaskContinuation;
4694  if (taskContinuation != null)
4695  {
4696  return taskContinuation.GetDelegateContinuationsForDebugger();
4697  }
4698  Task task = continuationObject as Task;
4699  if (task != null)
4700  {
4701  Delegate[] delegateContinuationsForDebugger = task.GetDelegateContinuationsForDebugger();
4702  if (delegateContinuationsForDebugger != null)
4703  {
4704  return delegateContinuationsForDebugger;
4705  }
4706  }
4707  ITaskCompletionAction taskCompletionAction = continuationObject as ITaskCompletionAction;
4708  if (taskCompletionAction != null)
4709  {
4710  Delegate[] obj = new Delegate[1];
4711  ITaskCompletionAction taskCompletionAction2 = taskCompletionAction;
4712  obj[0] = new Action<Task>(taskCompletionAction2.Invoke);
4713  return obj;
4714  }
4715  List<object> list = continuationObject as List<object>;
4716  if (list != null)
4717  {
4718  List<Delegate> list2 = new List<Delegate>();
4719  foreach (object item in list)
4720  {
4721  Delegate[] delegatesFromContinuationObject = GetDelegatesFromContinuationObject(item);
4722  if (delegatesFromContinuationObject != null)
4723  {
4724  Delegate[] array = delegatesFromContinuationObject;
4725  foreach (Delegate @delegate in array)
4726  {
4727  if ((object)@delegate != null)
4728  {
4729  list2.Add(@delegate);
4730  }
4731  }
4732  }
4733  }
4734  return list2.ToArray();
4735  }
4736  }
4737  return null;
4738  }
4739 
4740  private static Task GetActiveTaskFromId(int taskId)
4741  {
4742  Task value = null;
4743  s_currentActiveTasks.TryGetValue(taskId, out value);
4744  return value;
4745  }
4746 
4747  private static Task[] GetActiveTasks()
4748  {
4749  return new List<Task>(s_currentActiveTasks.Values).ToArray();
4750  }
4751  }
4752 }
static Task< Task > WhenAny(params Task[] tasks)
Creates a task that will complete when any of the supplied tasks have completed.
Definition: Task.cs:4588
static new TaskFactory< TResult > Factory
Provides access to factory methods for creating and configuring T:System.Threading....
Definition: Task.cs:75
bool Wait(int millisecondsTimeout, CancellationToken cancellationToken)
Waits for the T:System.Threading.Tasks.Task to complete execution. The wait terminates if a timeout i...
Definition: Task.cs:2874
static Task< TResult[]> WhenAll< TResult >(IEnumerable< Task< TResult >> tasks)
Creates a task that will complete when all of the T:System.Threading.Tasks.Task`1 objects in an enume...
Definition: Task.cs:4504
static TaskScheduler?? Current
Gets the T:System.Threading.Tasks.TaskScheduler associated with the currently executing task.
The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method th...
Task ContinueWith(Action< Task > continuationAction, TaskContinuationOptions continuationOptions)
Creates a continuation that executes when the target task completes according to the specified T:Syst...
Definition: Task.cs:3265
void Dispose()
Releases all resources used by the current instance of the T:System.Threading.ManualResetEventSlim cl...
Task(Func< TResult > function, TaskCreationOptions creationOptions)
Initializes a new T:System.Threading.Tasks.Task`1 with the specified function and creation options.
Definition: Task.cs:140
Propagates notification that operations should be canceled.
new ConfiguredTaskAwaitable< TResult > ConfigureAwait(bool continueOnCapturedContext)
Configures an awaiter used to await this T:System.Threading.Tasks.Task`1.
Definition: Task.cs:393
delegate void ContextCallback(object state)
Represents a method to be called within a new context.
Task(Func< TResult > function)
Initializes a new T:System.Threading.Tasks.Task`1 with the specified function.
Definition: Task.cs:112
Encapsulates operating system–specific objects that wait for exclusive access to shared resources.
Definition: WaitHandle.cs:15
void ThrowIfCancellationRequested()
Throws a T:System.OperationCanceledException if this token has had cancellation requested.
int Count
Gets the number of elements contained in the T:System.Collections.Generic.List`1.
Definition: List.cs:296
Task ContinueWith(Action< Task< TResult >, object > continuationAction, object state, CancellationToken cancellationToken)
Creates a continuation that executes when the target T:System.Threading.Tasks.Task`1 completes.
Definition: Task.cs:509
Task ContinueWith(Action< Task< TResult >> continuationAction, CancellationToken cancellationToken)
Creates a cancelable continuation that executes asynchronously when the target T:System....
Definition: Task.cs:419
TResult Result
Gets the result value of this T:System.Threading.Tasks.Task`1.
Definition: Task.cs:57
static Task WhenAll(params Task[] tasks)
Creates a task that will complete when all of the T:System.Threading.Tasks.Task objects in an array h...
Definition: Task.cs:4464
Provides the base class for a generic read-only collection.
static void SuppressFinalize(object obj)
Requests that the common language runtime not call the finalizer for the specified object.
Definition: GC.cs:308
void Start()
Starts the T:System.Threading.Tasks.Task, scheduling it for execution to the current T:System....
Definition: Task.cs:2003
static int WaitAny(Task[] tasks, TimeSpan timeout)
Waits for any of the provided T:System.Threading.Tasks.Task objects to complete execution within a sp...
Definition: Task.cs:4026
TaskStatus Status
Gets the T:System.Threading.Tasks.TaskStatus of this task.
Definition: Task.cs:1294
Task(Action< object > action, object state, TaskCreationOptions creationOptions)
Initializes a new T:System.Threading.Tasks.Task with the specified action, state, and options.
Definition: Task.cs:1740
static YieldAwaitable Yield()
Creates an awaitable task that asynchronously yields back to the current context when awaited.
Definition: Task.cs:2804
TaskStatus
Represents the current stage in the lifecycle of a T:System.Threading.Tasks.Task.
Definition: TaskStatus.cs:5
Represents an object that handles the low-level work of queuing tasks onto threads.
Task ContinueWith(Action< Task< TResult >, object > continuationAction, object state, TaskScheduler scheduler)
Creates a continuation that executes when the target T:System.Threading.Tasks.Task`1 completes.
Definition: Task.cs:524
Definition: __Canon.cs:3
TaskContinuationOptions
Specifies the behavior for a task that is created by using the M:System.Threading....
The exception that is thrown when the value of an argument is outside the allowable range of values a...
Task(Func< TResult > function, CancellationToken cancellationToken)
Initializes a new T:System.Threading.Tasks.Task`1 with the specified function.
Definition: Task.cs:126
static Task< Task > WhenAny(IEnumerable< Task > tasks)
Creates a task that will complete when any of the supplied tasks have completed.
Definition: Task.cs:4618
void Start(TaskScheduler scheduler)
Starts the T:System.Threading.Tasks.Task, scheduling it for execution to the specified T:System....
Definition: Task.cs:2015
static void KeepAlive(object obj)
References the specified object, which makes it ineligible for garbage collection from the start of t...
Definition: GC.cs:267
static Task Run(Func< Task > function)
Queues the specified work to run on the thread pool and returns a proxy for the task returned by func...
Definition: Task.cs:4264
static Task Delay(int millisecondsDelay)
Creates a task that completes after a time delay.
Definition: Task.cs:4368
double TotalMilliseconds
Gets the value of the current T:System.TimeSpan structure expressed in whole and fractional milliseco...
Definition: TimeSpan.cs:180
static bool WaitAll(Task[] tasks, TimeSpan timeout)
Waits for all of the provided cancellable T:System.Threading.Tasks.Task objects to complete execution...
Definition: Task.cs:3766
bool CanBeCanceled
Gets whether this token is capable of being in the canceled state.
void RunSynchronously(TaskScheduler scheduler)
Runs the T:System.Threading.Tasks.Task synchronously on the T:System.Threading.Tasks....
Definition: Task.cs:2057
static Task Delay(TimeSpan delay)
Creates a task that completes after a specified time interval.
Definition: Task.cs:4339
Task ContinueWith(Action< Task, object > continuationAction, object state, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
Creates a continuation that receives caller-supplied state information and a cancellation token and t...
Definition: Task.cs:3375
Exposes the enumerator, which supports a simple iteration over a collection of a specified type....
Definition: IEnumerable.cs:9
delegate void Action()
Encapsulates a method that has no parameters and does not return a value.
static bool WaitAll(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
Waits for all of the provided T:System.Threading.Tasks.Task objects to complete execution within a sp...
Definition: Task.cs:3824
WaitHandle WaitHandle
Gets the underlying T:System.Threading.WaitHandle object for this T:System.Threading....
Task(Action< object > action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
Initializes a new T:System.Threading.Tasks.Task with the specified action, state, and options.
Definition: Task.cs:1757
static int WaitAny(Task[] tasks, int millisecondsTimeout)
Waits for any of the provided T:System.Threading.Tasks.Task objects to complete execution within a sp...
Definition: Task.cs:4062
Task(Func< object, TResult > function, object state, CancellationToken cancellationToken)
Initializes a new T:System.Threading.Tasks.Task`1 with the specified action, state,...
Definition: Task.cs:184
bool IsCancellationRequested
Gets whether cancellation has been requested for this token.
static Task Run(Func< Task > function, CancellationToken cancellationToken)
Queues the specified work to run on the thread pool and returns a proxy for the task returned by func...
Definition: Task.cs:4277
Task ContinueWith(Action< Task, object > continuationAction, object state, TaskScheduler scheduler)
Creates a continuation that receives caller-supplied state information and executes asynchronously wh...
Definition: Task.cs:3341
Defines methods to manipulate generic collections.
Definition: ICollection.cs:9
Represents one or more errors that occur during application execution.
TaskCreationOptions
Specifies flags that control optional behavior for the creation and execution of tasks.
Task ContinueWith(Action< Task > continuationAction, TaskScheduler scheduler)
Creates a continuation that executes asynchronously when the target T:System.Threading....
Definition: Task.cs:3251
static void WaitAll(params Task[] tasks)
Waits for all of the provided T:System.Threading.Tasks.Task objects to complete execution.
Definition: Task.cs:3747
bool IsFaulted
Gets whether the T:System.Threading.Tasks.Task completed due to an unhandled exception.
Definition: Task.cs:1523
Provides the context for waiting when asynchronously switching into a target environment.
The exception that is thrown when an operation is performed on a disposed object.
Represents an exception whose state is captured at a certain point in code.
static TaskScheduler Default
Gets the default T:System.Threading.Tasks.TaskScheduler instance that is provided by the ....
void Add(T item)
Adds an object to the end of the T:System.Collections.Generic.List`1.
Definition: List.cs:510
static Task FromCanceled(CancellationToken cancellationToken)
Creates a T:System.Threading.Tasks.Task that's completed due to cancellation with a specified cancell...
Definition: Task.cs:4166
SecurityAction
Specifies the security actions that can be performed using declarative security.
Task ContinueWith(Action< Task< TResult >, object > continuationAction, object state, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
Creates a continuation that executes when the target T:System.Threading.Tasks.Task`1 completes.
Definition: Task.cs:558
The server synchronously processed the message.
Provides information about, and means to manipulate, the current environment and platform....
Definition: Environment.cs:21
Represents the status of an asynchronous operation.
Definition: IAsyncResult.cs:9
Manages the execution context for the current thread. This class cannot be inherited.
Provides an object that waits for the completion of an asynchronous task.
Definition: TaskAwaiter.cs:14
static Task< TResult > FromException< TResult >(Exception exception)
Creates a T:System.Threading.Tasks.Task`1 that's completed with a specified exception.
Definition: Task.cs:4140
static Task Delay(int millisecondsDelay, CancellationToken cancellationToken)
Creates a cancellable task that completes after a time delay.
Definition: Task.cs:4381
TaskAwaiter GetAwaiter()
Gets an awaiter used to await this T:System.Threading.Tasks.Task.
Definition: Task.cs:2749
void Set()
Sets the state of the event to signaled, which allows one or more threads waiting on the event to pro...
Task ContinueWith(Action< Task, object > continuationAction, object state, TaskContinuationOptions continuationOptions)
Creates a continuation that receives caller-supplied state information and executes when the target T...
Definition: Task.cs:3356
bool IsCompleted
Gets whether this T:System.Threading.Tasks.Task has completed.
Definition: Task.cs:1370
Task(Action action)
Initializes a new T:System.Threading.Tasks.Task with the specified action.
Definition: Task.cs:1653
void Insert(int index, T item)
Inserts an element into the T:System.Collections.Generic.List`1 at the specified index.
Definition: List.cs:1141
static void SetCurrentThreadActivityId(Guid activityId)
[Supported in the .NET Framework 4.5.1 and later versions] Sets the activity ID on the current thread...
Definition: EventSource.cs:649
static int CompareExchange(ref int location1, int value, int comparand)
Compares two 32-bit signed integers for equality and, if they are equal, replaces the first value.
Task(Func< object, TResult > function, object state, TaskCreationOptions creationOptions)
Initializes a new T:System.Threading.Tasks.Task`1 with the specified action, state,...
Definition: Task.cs:199
Task< TNewResult > ContinueWith< TNewResult >(Func< Task< TResult >, TNewResult > continuationFunction)
Creates a continuation that executes asynchronously when the target T:System.Threading....
Definition: Task.cs:588
Task(Action< object > action, object state, CancellationToken cancellationToken)
Initializes a new T:System.Threading.Tasks.Task with the specified action, state, and options.
Definition: Task.cs:1725
static Task FromException(Exception exception)
Creates a T:System.Threading.Tasks.Task that has completed with a specified exception.
Definition: Task.cs:4130
CancellationToken CancellationToken
Gets a token associated with the operation that was canceled.
Task ContinueWith(Action< Task > continuationAction, CancellationToken cancellationToken)
Creates a continuation that receives a cancellation token and executes asynchronously when the target...
Definition: Task.cs:3237
TaskCreationOptions CreationOptions
Gets the T:System.Threading.Tasks.TaskCreationOptions used to create this task.
Definition: Task.cs:1385
object AsyncState
Gets the state object supplied when the T:System.Threading.Tasks.Task was created,...
Definition: Task.cs:1414
Provides a mechanism for executing a method on a thread pool thread at specified intervals....
Definition: Timer.cs:12
Provides the ability to create events for event tracing for Windows (ETW).
Definition: EventSource.cs:21
Provides a slimmed down version of T:System.Threading.ManualResetEvent.
void Wait(CancellationToken cancellationToken)
Waits for the T:System.Threading.Tasks.Task to complete execution. The wait terminates if a cancellat...
Definition: Task.cs:2844
Provides the basic functionality for propagating a synchronization context in various synchronization...
static Task Run(Action action, CancellationToken cancellationToken)
Queues the specified work to run on the thread pool and returns a T:System.Threading....
Definition: Task.cs:4224
Provides methods for creating, manipulating, searching, and sorting arrays, thereby serving as the ba...
Definition: Array.cs:17
static Task< TResult > FromCanceled< TResult >(CancellationToken cancellationToken)
Creates a T:System.Threading.Tasks.Task`1 that's completed due to cancellation with a specified cance...
Definition: Task.cs:4187
Represents a delegate, which is a data structure that refers to a static method or to a class instanc...
Definition: Delegate.cs:15
virtual void Dispose(bool disposing)
Disposes the T:System.Threading.Tasks.Task, releasing all of its unmanaged resources.
Definition: Task.cs:2200
static Task Delay(TimeSpan delay, CancellationToken cancellationToken)
Creates a cancellable task that completes after a specified time interval.
Definition: Task.cs:4353
Task ContinueWith(Action< Task, object > continuationAction, object state)
Creates a continuation that receives caller-supplied state information and executes when the target T...
Definition: Task.cs:3311
Task ContinueWith(Action< Task > continuationAction)
Creates a continuation that executes asynchronously when the target T:System.Threading....
Definition: Task.cs:3223
ConfiguredTaskAwaitable ConfigureAwait(bool continueOnCapturedContext)
Configures an awaiter used to await this T:System.Threading.Tasks.Task.
Definition: Task.cs:2759
bool? IsSet
Gets whether the event is set.
static Task CompletedTask
Gets a task that has already completed successfully.
Definition: Task.cs:1453
MethodImplOptions
Defines the details of how a method is implemented.
bool CompletedSynchronously
Gets a value that indicates whether the asynchronous operation completed synchronously.
Definition: IAsyncResult.cs:44
Enables communication with a debugger. This class cannot be inherited.
Definition: Debugger.cs:11
Task(Func< object, TResult > function, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
Initializes a new T:System.Threading.Tasks.Task`1 with the specified action, state,...
Definition: Task.cs:216
static CancellationToken None
Returns an empty T:System.Threading.CancellationToken value.
static int WaitAny(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
Waits for any of the provided T:System.Threading.Tasks.Task objects to complete execution within a sp...
Definition: Task.cs:4080
void Dispose()
Releases all resources used by the current instance of the T:System.Threading.Tasks....
Definition: Task.cs:2191
void RunSynchronously()
Runs the T:System.Threading.Tasks.Task synchronously on the current T:System.Threading....
Definition: Task.cs:2046
int Id
Gets an ID for this T:System.Threading.Tasks.Task instance.
Definition: Task.cs:1233
Controls the system garbage collector, a service that automatically reclaims unused memory.
Definition: GC.cs:11
Represents a collection of keys and values.To browse the .NET Framework source code for this type,...
Definition: Dictionary.cs:17
static Task WhenAll(IEnumerable< Task > tasks)
Creates a task that will complete when all of the T:System.Threading.Tasks.Task objects in an enumera...
Definition: Task.cs:4420
MethodInfo Method
Gets the method represented by the delegate.
Definition: Delegate.cs:34
static ExecutionContext Capture()
Captures the execution context from the current thread.
Provides an awaitable object that enables configured awaits on a task.
The exception that is thrown when one of the arguments provided to a method is not valid.
static Task< Task< TResult > > WhenAny< TResult >(params Task< TResult >[] tasks)
Creates a task that will complete when any of the supplied tasks have completed.
Definition: Task.cs:4647
An operation that invokes a delegate or lambda expression, such as sampleDelegate....
WaitHandle AsyncWaitHandle
Gets a T:System.Threading.WaitHandle that is used to wait for an asynchronous operation to complete.
Definition: IAsyncResult.cs:25
bool Wait(int millisecondsTimeout)
Waits for the T:System.Threading.Tasks.Task to complete execution within a specified number of millis...
Definition: Task.cs:2858
Task(Action action, CancellationToken cancellationToken)
Initializes a new T:System.Threading.Tasks.Task with the specified action and T:System....
Definition: Task.cs:1667
Represents a strongly typed list of objects that can be accessed by index. Provides methods to search...
Definition: List.cs:14
The exception that is thrown in a thread upon cancellation of an operation that the thread was execut...
void Wait()
Waits for the T:System.Threading.Tasks.Task to complete execution.
Definition: Task.cs:2813
Represents errors that occur during application execution.To browse the .NET Framework source code fo...
Definition: Exception.cs:22
AggregateException Exception
Gets the T:System.AggregateException that caused the T:System.Threading.Tasks.Task to end prematurely...
Definition: Task.cs:1277
static int WaitAny(params Task[] tasks)
Waits for any of the provided T:System.Threading.Tasks.Task objects to complete execution.
Definition: Task.cs:4009
ThreadState
Specifies the current execution state of the thread.
Definition: ThreadState.cs:4
bool Wait(TimeSpan timeout)
Waits for the T:System.Threading.Tasks.Task to complete execution within a specified time interval.
Definition: Task.cs:2828
static void WaitAll(Task[] tasks, CancellationToken cancellationToken)
Waits for all of the provided T:System.Threading.Tasks.Task objects to complete execution unless the ...
Definition: Task.cs:3804
Task ContinueWith(Action< Task< TResult >> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
Creates a continuation that executes according the condition specified in continuationOptions .
Definition: Task.cs:465
Task(Func< object, TResult > function, object state)
Initializes a new T:System.Threading.Tasks.Task`1 with the specified function and state.
Definition: Task.cs:169
Represents a time interval.To browse the .NET Framework source code for this type,...
Definition: TimeSpan.cs:12
static bool WaitAll(Task[] tasks, int millisecondsTimeout)
Waits for all of the provided T:System.Threading.Tasks.Task objects to complete execution within a sp...
Definition: Task.cs:3789
int Capacity
Gets or sets the total number of elements the internal data structure can hold without resizing.
Definition: List.cs:259
Task ContinueWith(Action< Task< TResult >> continuationAction, TaskContinuationOptions continuationOptions)
Creates a continuation that executes according the condition specified in continuationOptions .
Definition: Task.cs:448
static Task< TResult > FromResult< TResult >(TResult result)
Creates a T:System.Threading.Tasks.Task`1 that's completed successfully with the specified result.
Definition: Task.cs:4121
Task(Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
Initializes a new T:System.Threading.Tasks.Task with the specified action and creation options.
Definition: Task.cs:1697
static Task Run(Action action)
Queues the specified work to run on the thread pool and returns a T:System.Threading....
Definition: Task.cs:4209
The exception that is thrown when a method call is invalid for the object's current state.
Task ContinueWith(Action< Task, object > continuationAction, object state, CancellationToken cancellationToken)
Creates a continuation that receives caller-supplied state information and a cancellation token and t...
Definition: Task.cs:3326
int RemoveAll(Predicate< T > match)
Removes all the elements that match the conditions defined by the specified predicate.
Definition: List.cs:1337
Task ContinueWith(Action< Task< TResult >> continuationAction)
Creates a continuation that executes asynchronously when the target task completes.
Definition: Task.cs:405
Task(Action action, TaskCreationOptions creationOptions)
Initializes a new T:System.Threading.Tasks.Task with the specified action and creation options.
Definition: Task.cs:1681
Task< TResult > ContinueWith< TResult >(Func< Task, TResult > continuationFunction)
Creates a continuation that executes asynchronously when the target T:System.Threading....
Definition: Task.cs:3405
Task ContinueWith(Action< Task< TResult >, object > continuationAction, object state)
Creates a continuation that that is passed state information and that executes when the target T:Syst...
Definition: Task.cs:494
new TaskAwaiter< TResult > GetAwaiter()
Gets an awaiter used to await this T:System.Threading.Tasks.Task`1.
Definition: Task.cs:384
static void NotifyOfCrossThreadDependency()
Notifies a debugger that execution is about to enter a path that involves a cross-thread dependency.
Definition: Debugger.cs:104
Provides support for creating and scheduling T:System.Threading.Tasks.Task`1 objects.
Definition: TaskFactory.cs:12
Task ContinueWith(Action< Task< TResult >, object > continuationAction, object state, TaskContinuationOptions continuationOptions)
Creates a continuation that executes when the target T:System.Threading.Tasks.Task`1 completes.
Definition: Task.cs:539
T [] ToArray()
Copies the elements of the T:System.Collections.Generic.List`1 to a new array.
Definition: List.cs:1531
Task(Action< object > action, object state)
Initializes a new T:System.Threading.Tasks.Task with the specified action and state.
Definition: Task.cs:1710
Task(Func< TResult > function, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
Initializes a new T:System.Threading.Tasks.Task`1 with the specified function and creation options.
Definition: Task.cs:156
DebuggerBrowsableState
Provides display instructions for the debugger.
static Task< TResult > Run< TResult >(Func< TResult > function)
Queues the specified work to run on the thread pool and returns a T:System.Threading....
Definition: Task.cs:4237
Provides atomic operations for variables that are shared by multiple threads.
Definition: Interlocked.cs:10
Task ContinueWith(Action< Task > continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
Creates a continuation that executes when the target task competes according to the specified T:Syste...
Definition: Task.cs:3282
static ? int? CurrentId
Returns the ID of the currently executing T:System.Threading.Tasks.Task.
Definition: Task.cs:1250
static int WaitAny(Task[] tasks, CancellationToken cancellationToken)
Waits for any of the provided T:System.Threading.Tasks.Task objects to complete execution unless the ...
Definition: Task.cs:4046
Task ContinueWith(Action< Task< TResult >> continuationAction, TaskScheduler scheduler)
Creates a continuation that executes asynchronously when the target T:System.Threading....
Definition: Task.cs:433
Attribute can be applied to a delegate.
bool IsCanceled
Gets whether this T:System.Threading.Tasks.Task instance has completed execution due to being cancele...
Definition: Task.cs:1336
Represents an asynchronous operation that can return a value.
Definition: Task.cs:18