5 // Marek Safar <marek.safar@gmail.com>
6 // Jérémie Laval <jeremie dot laval at xamarin dot com>
8 // Copyright (c) 2008 Jérémie "Garuma" Laval
9 // Copyright 2011 Xamarin Inc (http://www.xamarin.com).
11 // Permission is hereby granted, free of charge, to any person obtaining a copy
12 // of this software and associated documentation files (the "Software"), to deal
13 // in the Software without restriction, including without limitation the rights
14 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15 // copies of the Software, and to permit persons to whom the Software is
16 // furnished to do so, subject to the following conditions:
18 // The above copyright notice and this permission notice shall be included in
19 // all copies or substantial portions of the Software.
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
34 using System.Threading;
35 using System.Collections.Concurrent;
36 using System.Collections.Generic;
37 using System.Runtime.CompilerServices;
39 namespace System.Threading.Tasks
41 [System.Diagnostics.DebuggerDisplay ("Id = {Id}, Status = {Status}")]
42 [System.Diagnostics.DebuggerTypeProxy (typeof (TaskDebuggerView))]
43 public class Task : IDisposable, IAsyncResult
45 // With this attribute each thread has its own value so that it's correct for our Schedule code
46 // and for Parent property.
50 static Action<Task> childWorkAdder;
52 // parent is the outer task in which this task is created
54 // contAncestor is the Task on which this continuation was setup
55 readonly Task contAncestor;
58 static readonly TaskFactory defaultFactory = new TaskFactory ();
60 CountdownEvent childTasks;
63 TaskCreationOptions creationOptions;
65 internal TaskScheduler scheduler;
67 TaskExceptionSlot exSlot;
71 TaskActionInvoker invoker;
73 internal AtomicBooleanValue executing;
75 TaskCompletionQueue<IContinuation> continuations;
77 CancellationToken token;
78 CancellationTokenRegistration? cancellationRegistration;
80 internal const TaskCreationOptions WorkerTaskNotSupportedOptions = TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness;
82 const TaskCreationOptions MaxTaskCreationOptions =
84 TaskCreationOptions.DenyChildAttach | TaskCreationOptions.HideScheduler |
86 TaskCreationOptions.PreferFairness | TaskCreationOptions.LongRunning | TaskCreationOptions.AttachedToParent;
88 public Task (Action action)
89 : this (action, TaskCreationOptions.None)
94 public Task (Action action, TaskCreationOptions creationOptions)
95 : this (action, CancellationToken.None, creationOptions)
100 public Task (Action action, CancellationToken cancellationToken)
101 : this (action, cancellationToken, TaskCreationOptions.None)
106 public Task (Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
107 : this (TaskActionInvoker.Create (action), null, cancellationToken, creationOptions, current)
110 throw new ArgumentNullException ("action");
111 if (creationOptions > MaxTaskCreationOptions || creationOptions < TaskCreationOptions.None)
112 throw new ArgumentOutOfRangeException ("creationOptions");
115 public Task (Action<object> action, object state)
116 : this (action, state, TaskCreationOptions.None)
120 public Task (Action<object> action, object state, TaskCreationOptions creationOptions)
121 : this (action, state, CancellationToken.None, creationOptions)
125 public Task (Action<object> action, object state, CancellationToken cancellationToken)
126 : this (action, state, cancellationToken, TaskCreationOptions.None)
130 public Task (Action<object> action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
131 : this (TaskActionInvoker.Create (action), state, cancellationToken, creationOptions, current)
134 throw new ArgumentNullException ("action");
135 if (creationOptions > MaxTaskCreationOptions || creationOptions < TaskCreationOptions.None)
136 throw new ArgumentOutOfRangeException ("creationOptions");
139 internal Task (TaskActionInvoker invoker, object state, CancellationToken cancellationToken,
140 TaskCreationOptions creationOptions, Task parent = null, Task contAncestor = null, bool ignoreCancellation = false)
142 this.invoker = invoker;
143 this.creationOptions = creationOptions;
145 this.taskId = Interlocked.Increment (ref id);
146 this.token = cancellationToken;
147 this.parent = parent = parent == null ? current : parent;
148 this.contAncestor = contAncestor;
149 this.status = cancellationToken.IsCancellationRequested && !ignoreCancellation ? TaskStatus.Canceled : TaskStatus.Created;
151 // Process creationOptions
153 if (HasFlag (creationOptions, TaskCreationOptions.AttachedToParent)
154 && parent != null && !HasFlag (parent.CreationOptions, TaskCreationOptions.DenyChildAttach))
156 if (HasFlag (creationOptions, TaskCreationOptions.AttachedToParent) && parent != null)
160 if (token.CanBeCanceled && !ignoreCancellation)
161 cancellationRegistration = token.Register (l => ((Task) l).CancelReal (), this);
164 static bool HasFlag (TaskCreationOptions opt, TaskCreationOptions member)
166 return (opt & member) == member;
172 Start (TaskScheduler.Current);
175 public void Start (TaskScheduler scheduler)
177 if (scheduler == null)
178 throw new ArgumentNullException ("scheduler");
180 if (status >= TaskStatus.WaitingToRun)
181 throw new InvalidOperationException ("The Task is not in a valid state to be started.");
184 throw new InvalidOperationException ("Start may not be called on a continuation task");
186 SetupScheduler (scheduler);
190 internal void SetupScheduler (TaskScheduler scheduler)
192 this.scheduler = scheduler;
193 Status = TaskStatus.WaitingForActivation;
196 public void RunSynchronously ()
198 RunSynchronously (TaskScheduler.Current);
201 public void RunSynchronously (TaskScheduler scheduler)
203 if (scheduler == null)
204 throw new ArgumentNullException ("scheduler");
206 if (Status > TaskStatus.WaitingForActivation)
207 throw new InvalidOperationException ("The task is not in a valid state to be started");
209 SetupScheduler (scheduler);
210 var saveStatus = status;
211 Status = TaskStatus.WaitingToRun;
214 if (scheduler.RunInline (this, false))
216 } catch (Exception inner) {
217 throw new TaskSchedulerException (inner);
227 public Task ContinueWith (Action<Task> continuationAction)
229 return ContinueWith (continuationAction, TaskContinuationOptions.None);
232 public Task ContinueWith (Action<Task> continuationAction, TaskContinuationOptions continuationOptions)
234 return ContinueWith (continuationAction, CancellationToken.None, continuationOptions, TaskScheduler.Current);
237 public Task ContinueWith (Action<Task> continuationAction, CancellationToken cancellationToken)
239 return ContinueWith (continuationAction, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
242 public Task ContinueWith (Action<Task> continuationAction, TaskScheduler scheduler)
244 return ContinueWith (continuationAction, CancellationToken.None, TaskContinuationOptions.None, scheduler);
247 public Task ContinueWith (Action<Task> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
249 if (continuationAction == null)
250 throw new ArgumentNullException ("continuationAction");
251 if (scheduler == null)
252 throw new ArgumentNullException ("scheduler");
254 return ContinueWith (TaskActionInvoker.Create (continuationAction), cancellationToken, continuationOptions, scheduler);
257 internal Task ContinueWith (TaskActionInvoker invoker, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
259 var lazyCancellation = false;
261 lazyCancellation = (continuationOptions & TaskContinuationOptions.LazyCancellation) > 0;
263 var continuation = new Task (invoker, null, cancellationToken, GetCreationOptions (continuationOptions), null, this, lazyCancellation);
264 ContinueWithCore (continuation, continuationOptions, scheduler);
269 public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction)
271 return ContinueWith<TResult> (continuationFunction, TaskContinuationOptions.None);
274 public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, TaskContinuationOptions continuationOptions)
276 return ContinueWith<TResult> (continuationFunction, CancellationToken.None, continuationOptions, TaskScheduler.Current);
279 public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, CancellationToken cancellationToken)
281 return ContinueWith<TResult> (continuationFunction, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
284 public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, TaskScheduler scheduler)
286 return ContinueWith<TResult> (continuationFunction, CancellationToken.None, TaskContinuationOptions.None, scheduler);
289 public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, CancellationToken cancellationToken,
290 TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
292 if (continuationFunction == null)
293 throw new ArgumentNullException ("continuationFunction");
294 if (scheduler == null)
295 throw new ArgumentNullException ("scheduler");
297 return ContinueWith<TResult> (TaskActionInvoker.Create (continuationFunction), cancellationToken, continuationOptions, scheduler);
300 internal Task<TResult> ContinueWith<TResult> (TaskActionInvoker invoker, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
302 var lazyCancellation = false;
304 lazyCancellation = (continuationOptions & TaskContinuationOptions.LazyCancellation) > 0;
306 var continuation = new Task<TResult> (invoker, null, cancellationToken, GetCreationOptions (continuationOptions), parent, this, lazyCancellation);
307 ContinueWithCore (continuation, continuationOptions, scheduler);
312 internal void ContinueWithCore (Task continuation, TaskContinuationOptions options, TaskScheduler scheduler)
314 const TaskContinuationOptions wrongRan = TaskContinuationOptions.NotOnRanToCompletion | TaskContinuationOptions.OnlyOnRanToCompletion;
315 const TaskContinuationOptions wrongCanceled = TaskContinuationOptions.NotOnCanceled | TaskContinuationOptions.OnlyOnCanceled;
316 const TaskContinuationOptions wrongFaulted = TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.OnlyOnFaulted;
318 if (((options & wrongRan) == wrongRan) || ((options & wrongCanceled) == wrongCanceled) || ((options & wrongFaulted) == wrongFaulted))
319 throw new ArgumentException ("continuationOptions", "Some options are mutually exclusive");
321 // Already set the scheduler so that user can call Wait and that sort of stuff
322 continuation.scheduler = scheduler;
323 continuation.Status = TaskStatus.WaitingForActivation;
325 ContinueWith (new TaskContinuation (continuation, options));
328 internal void ContinueWith (IContinuation continuation)
331 continuation.Execute ();
335 continuations.Add (continuation);
337 // Retry in case completion was achieved but event adding was too late
338 if (IsCompleted && continuations.Remove (continuation))
339 continuation.Execute ();
342 void RemoveContinuation (IContinuation continuation)
344 continuations.Remove (continuation);
347 static internal TaskCreationOptions GetCreationOptions (TaskContinuationOptions kind)
349 TaskCreationOptions options = TaskCreationOptions.None;
350 if ((kind & TaskContinuationOptions.AttachedToParent) > 0)
351 options |= TaskCreationOptions.AttachedToParent;
352 if ((kind & TaskContinuationOptions.PreferFairness) > 0)
353 options |= TaskCreationOptions.PreferFairness;
354 if ((kind & TaskContinuationOptions.LongRunning) > 0)
355 options |= TaskCreationOptions.LongRunning;
361 #region Internal and protected thingies
362 internal void Schedule ()
364 Status = TaskStatus.WaitingToRun;
366 // If worker is null it means it is a local one, revert to the old behavior
367 // If TaskScheduler.Current is not being used, the scheduler was explicitly provided, so we must use that
368 if (scheduler != TaskScheduler.Current || childWorkAdder == null || HasFlag (creationOptions, TaskCreationOptions.PreferFairness)) {
369 scheduler.QueueTask (this);
371 /* Like the semantic of the ABP paper describe it, we add ourselves to the bottom
372 * of our Parent Task's ThreadWorker deque. It's ok to do that since we are in
373 * the correct Thread during the creation
375 childWorkAdder (this);
381 /* Allow scheduler to break fairness of deque ordering without
382 * breaking its semantic (the task can be executed twice but the
383 * second time it will return immediately
385 if (!executing.TryRelaxedSet ())
388 // Disable CancellationToken direct cancellation
389 if (cancellationRegistration != null) {
390 cancellationRegistration.Value.Dispose ();
391 cancellationRegistration = null;
394 // If Task are ran inline on the same thread we might trash these values
395 var saveCurrent = current;
396 var saveScheduler = TaskScheduler.Current;
400 TaskScheduler.Current = HasFlag (creationOptions, TaskCreationOptions.HideScheduler) ? TaskScheduler.Default : scheduler;
402 TaskScheduler.Current = scheduler;
405 if (!token.IsCancellationRequested) {
407 status = TaskStatus.Running;
411 } catch (OperationCanceledException oce) {
412 if (token != CancellationToken.None && oce.CancellationToken == token)
415 HandleGenericException (oce);
416 } catch (Exception e) {
417 HandleGenericException (e);
423 if (saveCurrent != null)
424 current = saveCurrent;
425 if (saveScheduler != null)
426 TaskScheduler.Current = saveScheduler;
430 internal bool TrySetCanceled ()
435 if (!executing.TryRelaxedSet ()) {
436 var sw = new SpinWait ();
447 internal bool TrySetException (AggregateException aggregate)
452 if (!executing.TryRelaxedSet ()) {
453 var sw = new SpinWait ();
460 HandleGenericException (aggregate);
464 internal bool TrySetExceptionObserved ()
466 if (exSlot != null) {
467 exSlot.Observed = true;
473 internal void Execute ()
478 internal void AddChild ()
480 if (childTasks == null)
481 Interlocked.CompareExchange (ref childTasks, new CountdownEvent (1), null);
482 childTasks.AddCount ();
485 internal void ChildCompleted (AggregateException childEx)
487 if (childEx != null) {
488 if (ExceptionSlot.ChildExceptions == null)
489 Interlocked.CompareExchange (ref ExceptionSlot.ChildExceptions, new ConcurrentQueue<AggregateException> (), null);
490 ExceptionSlot.ChildExceptions.Enqueue (childEx);
493 if (childTasks.Signal () && status == TaskStatus.WaitingForChildrenToComplete) {
494 ProcessChildExceptions ();
495 Status = exSlot == null ? TaskStatus.RanToCompletion : TaskStatus.Faulted;
496 ProcessCompleteDelegates ();
497 if (HasFlag (creationOptions, TaskCreationOptions.AttachedToParent) && parent != null)
498 parent.ChildCompleted (this.Exception);
504 if (IsContinuation) {
505 invoker.Invoke (contAncestor, state, this);
507 invoker.Invoke (this, state, this);
511 internal void Finish ()
513 // If there was children created and they all finished, we set the countdown
514 if (childTasks != null) {
515 if (childTasks.Signal ())
516 ProcessChildExceptions (true);
519 // Don't override Canceled or Faulted
520 if (status == TaskStatus.Running) {
521 if (childTasks == null || childTasks.IsSet)
522 Status = TaskStatus.RanToCompletion;
524 Status = TaskStatus.WaitingForChildrenToComplete;
527 // Completions are already processed when task is canceled or faulted
528 if (status == TaskStatus.RanToCompletion)
529 ProcessCompleteDelegates ();
531 // Reset the current thingies
534 if (TaskScheduler.Current == scheduler)
535 TaskScheduler.Current = null;
537 if (cancellationRegistration.HasValue)
538 cancellationRegistration.Value.Dispose ();
540 // Tell parent that we are finished
541 if (HasFlag (creationOptions, TaskCreationOptions.AttachedToParent) && parent != null && status != TaskStatus.WaitingForChildrenToComplete) {
542 parent.ChildCompleted (this.Exception);
546 void ProcessCompleteDelegates ()
548 if (continuations.HasElements) {
549 IContinuation continuation;
550 while (continuations.TryGetNextCompletion (out continuation))
551 continuation.Execute ();
555 void ProcessChildExceptions (bool isParent = false)
557 if (exSlot == null || exSlot.ChildExceptions == null)
560 if (ExceptionSlot.Exception == null)
561 exSlot.Exception = new AggregateException ();
563 AggregateException childEx;
564 while (exSlot.ChildExceptions.TryDequeue (out childEx))
565 exSlot.Exception.AddChildException (childEx);
568 Status = TaskStatus.Faulted;
569 ProcessCompleteDelegates ();
574 #region Cancel and Wait related method
576 internal void CancelReal ()
578 Status = TaskStatus.Canceled;
579 ProcessCompleteDelegates ();
582 void HandleGenericException (Exception e)
584 HandleGenericException (new AggregateException (e));
587 void HandleGenericException (AggregateException e)
589 ExceptionSlot.Exception = e;
590 Thread.MemoryBarrier ();
591 Status = TaskStatus.Faulted;
592 ProcessCompleteDelegates ();
595 internal bool WaitOnChildren ()
597 if (Status == TaskStatus.WaitingForChildrenToComplete && childTasks != null) {
606 Wait (Timeout.Infinite, CancellationToken.None);
609 public void Wait (CancellationToken cancellationToken)
611 Wait (Timeout.Infinite, cancellationToken);
614 public bool Wait (TimeSpan timeout)
616 return Wait (CheckTimeout (timeout), CancellationToken.None);
619 public bool Wait (int millisecondsTimeout)
621 return Wait (millisecondsTimeout, CancellationToken.None);
624 public bool Wait (int millisecondsTimeout, CancellationToken cancellationToken)
626 if (millisecondsTimeout < -1)
627 throw new ArgumentOutOfRangeException ("millisecondsTimeout");
632 // If the task is ready to be run and we were supposed to wait on it indefinitely without cancellation, just run it
633 if (Status == TaskStatus.WaitingToRun && millisecondsTimeout == Timeout.Infinite && scheduler != null && !cancellationToken.CanBeCanceled)
634 scheduler.RunInline (this, true);
637 var continuation = new ManualResetContinuation ();
639 ContinueWith (continuation);
640 result = continuation.Event.Wait (millisecondsTimeout, cancellationToken);
643 RemoveContinuation (continuation);
644 continuation.Dispose ();
650 throw new AggregateException (new TaskCanceledException (this));
652 var exception = Exception;
653 if (exception != null)
656 if (childTasks != null)
662 public static void WaitAll (params Task[] tasks)
664 WaitAll (tasks, Timeout.Infinite, CancellationToken.None);
667 public static void WaitAll (Task[] tasks, CancellationToken cancellationToken)
669 WaitAll (tasks, Timeout.Infinite, cancellationToken);
672 public static bool WaitAll (Task[] tasks, TimeSpan timeout)
674 return WaitAll (tasks, CheckTimeout (timeout), CancellationToken.None);
677 public static bool WaitAll (Task[] tasks, int millisecondsTimeout)
679 return WaitAll (tasks, millisecondsTimeout, CancellationToken.None);
682 public static bool WaitAll (Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
685 throw new ArgumentNullException ("tasks");
688 foreach (var t in tasks) {
690 throw new ArgumentException ("tasks", "the tasks argument contains a null element");
692 result &= t.Status == TaskStatus.RanToCompletion;
696 var continuation = new CountdownContinuation (tasks.Length);
698 foreach (var t in tasks)
699 t.ContinueWith (continuation);
701 result = continuation.Event.Wait (millisecondsTimeout, cancellationToken);
703 List<Exception> exceptions = null;
705 foreach (var t in tasks) {
707 if (t.Status == TaskStatus.RanToCompletion)
709 if (exceptions == null)
710 exceptions = new List<Exception> ();
711 if (t.Exception != null)
712 exceptions.AddRange (t.Exception.InnerExceptions);
714 exceptions.Add (new TaskCanceledException (t));
716 t.RemoveContinuation (continuation);
720 continuation.Dispose ();
722 if (exceptions != null)
723 throw new AggregateException (exceptions);
730 public static int WaitAny (params Task[] tasks)
732 return WaitAny (tasks, Timeout.Infinite, CancellationToken.None);
735 public static int WaitAny (Task[] tasks, TimeSpan timeout)
737 return WaitAny (tasks, CheckTimeout (timeout));
740 public static int WaitAny (Task[] tasks, int millisecondsTimeout)
742 return WaitAny (tasks, millisecondsTimeout, CancellationToken.None);
745 public static int WaitAny (Task[] tasks, CancellationToken cancellationToken)
747 return WaitAny (tasks, Timeout.Infinite, cancellationToken);
750 public static int WaitAny (Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
753 throw new ArgumentNullException ("tasks");
754 if (millisecondsTimeout < -1)
755 throw new ArgumentOutOfRangeException ("millisecondsTimeout");
756 CheckForNullTasks (tasks);
758 if (tasks.Length > 0) {
759 var continuation = new ManualResetContinuation ();
762 for (int i = 0; i < tasks.Length; i++) {
766 t.ContinueWith (continuation);
769 if (!(result = continuation.Event.Wait (millisecondsTimeout, cancellationToken)))
773 foreach (var t in tasks)
774 t.RemoveContinuation (continuation);
775 continuation.Dispose ();
779 int firstFinished = -1;
780 for (int i = 0; i < tasks.Length; i++) {
788 return firstFinished;
791 static int CheckTimeout (TimeSpan timeout)
794 return checked ((int)timeout.TotalMilliseconds);
795 } catch (System.OverflowException) {
796 throw new ArgumentOutOfRangeException ("timeout");
800 static void CheckForNullTasks (Task[] tasks)
802 foreach (var t in tasks)
804 throw new ArgumentException ("tasks", "the tasks argument contains a null element");
809 public void Dispose ()
814 protected virtual void Dispose (bool disposing)
817 throw new InvalidOperationException ("A task may only be disposed if it is in a completion state");
819 // Set action to null so that the GC can collect the delegate and thus
820 // any big object references that the user might have captured in a anonymous method
824 if (cancellationRegistration != null)
825 cancellationRegistration.Value.Dispose ();
832 public ConfiguredTaskAwaitable ConfigureAwait (bool continueOnCapturedContext)
834 return new ConfiguredTaskAwaitable (this, continueOnCapturedContext);
837 public Task ContinueWith (Action<Task, object> continuationAction, object state)
839 return ContinueWith (continuationAction, state, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Current);
842 public Task ContinueWith (Action<Task, object> continuationAction, object state, CancellationToken cancellationToken)
844 return ContinueWith (continuationAction, state, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
847 public Task ContinueWith (Action<Task, object> continuationAction, object state, TaskContinuationOptions continuationOptions)
849 return ContinueWith (continuationAction, state, CancellationToken.None, continuationOptions, TaskScheduler.Current);
852 public Task ContinueWith (Action<Task, object> continuationAction, object state, TaskScheduler scheduler)
854 return ContinueWith (continuationAction, state, CancellationToken.None, TaskContinuationOptions.None, scheduler);
857 public Task ContinueWith (Action<Task, object> continuationAction, object state, CancellationToken cancellationToken,
858 TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
860 if (continuationAction == null)
861 throw new ArgumentNullException ("continuationAction");
862 if (scheduler == null)
863 throw new ArgumentNullException ("scheduler");
865 Task continuation = new Task (TaskActionInvoker.Create (continuationAction),
866 state, cancellationToken,
867 GetCreationOptions (continuationOptions),
870 ContinueWithCore (continuation, continuationOptions, scheduler);
875 public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state)
877 return ContinueWith<TResult> (continuationFunction, state, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Current);
880 public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state, TaskContinuationOptions continuationOptions)
882 return ContinueWith<TResult> (continuationFunction, state, CancellationToken.None, continuationOptions, TaskScheduler.Current);
885 public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state, CancellationToken cancellationToken)
887 return ContinueWith<TResult> (continuationFunction, state, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
890 public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state, TaskScheduler scheduler)
892 return ContinueWith<TResult> (continuationFunction, state, CancellationToken.None, TaskContinuationOptions.None, scheduler);
895 public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state, CancellationToken cancellationToken,
896 TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
898 if (continuationFunction == null)
899 throw new ArgumentNullException ("continuationFunction");
900 if (scheduler == null)
901 throw new ArgumentNullException ("scheduler");
903 var t = new Task<TResult> (TaskActionInvoker.Create (continuationFunction),
906 GetCreationOptions (continuationOptions),
910 ContinueWithCore (t, continuationOptions, scheduler);
915 public static Task Delay (int millisecondsDelay)
917 return Delay (millisecondsDelay, CancellationToken.None);
920 public static Task Delay (TimeSpan delay)
922 return Delay (CheckTimeout (delay), CancellationToken.None);
925 public static Task Delay (TimeSpan delay, CancellationToken cancellationToken)
927 return Delay (CheckTimeout (delay), cancellationToken);
930 public static Task Delay (int millisecondsDelay, CancellationToken cancellationToken)
932 if (millisecondsDelay < -1)
933 throw new ArgumentOutOfRangeException ("millisecondsDelay");
935 var task = new Task (TaskActionInvoker.Delay, millisecondsDelay, cancellationToken, TaskCreationOptions.None, null, TaskConstants.Finished);
936 task.SetupScheduler (TaskScheduler.Current);
938 if (millisecondsDelay != Timeout.Infinite)
939 task.scheduler.QueueTask (task);
944 public static Task<TResult> FromResult<TResult> (TResult result)
946 var tcs = new TaskCompletionSource<TResult> ();
947 tcs.SetResult (result);
951 public TaskAwaiter GetAwaiter ()
953 return new TaskAwaiter (this);
956 public static Task Run (Action action)
958 return Run (action, CancellationToken.None);
961 public static Task Run (Action action, CancellationToken cancellationToken)
963 if (cancellationToken.IsCancellationRequested)
964 return TaskConstants.Canceled;
966 return Task.Factory.StartNew (action, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
969 public static Task Run (Func<Task> function)
971 return Run (function, CancellationToken.None);
974 public static Task Run (Func<Task> function, CancellationToken cancellationToken)
976 if (cancellationToken.IsCancellationRequested)
977 return TaskConstants.Canceled;
979 return TaskExtensions.Unwrap (Task.Factory.StartNew (function, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default));
982 public static Task<TResult> Run<TResult> (Func<TResult> function)
984 return Run (function, CancellationToken.None);
987 public static Task<TResult> Run<TResult> (Func<TResult> function, CancellationToken cancellationToken)
989 if (cancellationToken.IsCancellationRequested)
990 return TaskConstants<TResult>.Canceled;
992 return Task.Factory.StartNew (function, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
995 public static Task<TResult> Run<TResult> (Func<Task<TResult>> function)
997 return Run (function, CancellationToken.None);
1000 public static Task<TResult> Run<TResult> (Func<Task<TResult>> function, CancellationToken cancellationToken)
1002 if (cancellationToken.IsCancellationRequested)
1003 return TaskConstants<TResult>.Canceled;
1005 return TaskExtensions.Unwrap (Task.Factory.StartNew (function, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default));
1008 public static Task WhenAll (params Task[] tasks)
1011 throw new ArgumentNullException ("tasks");
1013 return WhenAllCore (tasks);
1016 public static Task WhenAll (IEnumerable<Task> tasks)
1019 throw new ArgumentNullException ("tasks");
1021 // Call ToList on input enumeration or we end up
1022 // enumerating it more than once
1023 return WhenAllCore (new List<Task> (tasks));
1026 public static Task<TResult[]> WhenAll<TResult> (params Task<TResult>[] tasks)
1029 throw new ArgumentNullException ("tasks");
1031 return WhenAllCore<TResult> (tasks);
1034 public static Task<TResult[]> WhenAll<TResult> (IEnumerable<Task<TResult>> tasks)
1037 throw new ArgumentNullException ("tasks");
1039 // Call ToList on input enumeration or we end up
1040 // enumerating it more than once
1041 return WhenAllCore<TResult> (new List<Task<TResult>> (tasks));
1044 internal static Task<TResult[]> WhenAllCore<TResult> (IList<Task<TResult>> tasks)
1046 foreach (var t in tasks) {
1048 throw new ArgumentException ("tasks", "the tasks argument contains a null element");
1051 var task = new Task<TResult[]> (TaskActionInvoker.Empty, null, CancellationToken.None, TaskCreationOptions.None, null, TaskConstants.Finished);
1052 task.SetupScheduler (TaskScheduler.Current);
1054 var continuation = new WhenAllContinuation<TResult> (task, tasks);
1055 foreach (var t in tasks)
1056 t.ContinueWith (continuation);
1061 public static Task<Task> WhenAny (params Task[] tasks)
1064 throw new ArgumentNullException ("tasks");
1066 return WhenAnyCore (tasks);
1069 public static Task<Task> WhenAny (IEnumerable<Task> tasks)
1072 throw new ArgumentNullException ("tasks");
1074 return WhenAnyCore (new List<Task> (tasks));
1077 public static Task<Task<TResult>> WhenAny<TResult> (params Task<TResult>[] tasks)
1080 throw new ArgumentNullException ("tasks");
1082 return WhenAnyCore<TResult> (tasks);
1085 public static Task<Task<TResult>> WhenAny<TResult> (IEnumerable<Task<TResult>> tasks)
1088 throw new ArgumentNullException ("tasks");
1090 return WhenAnyCore<TResult> (new List<Task<TResult>> (tasks));
1093 static Task<Task<TResult>> WhenAnyCore<TResult> (IList<Task<TResult>> tasks)
1095 if (tasks.Count == 0)
1096 throw new ArgumentException ("The tasks argument contains no tasks", "tasks");
1098 int completed_index = -1;
1099 for (int i = 0; i < tasks.Count; ++i) {
1102 throw new ArgumentException ("tasks", "the tasks argument contains a null element");
1104 if (t.IsCompleted && completed_index < 0)
1105 completed_index = i;
1108 var task = new Task<Task<TResult>> (TaskActionInvoker.Empty, null, CancellationToken.None, TaskCreationOptions.None, null, TaskConstants.Finished);
1110 if (completed_index > 0) {
1111 task.TrySetResult (tasks[completed_index]);
1115 task.SetupScheduler (TaskScheduler.Current);
1117 var continuation = new WhenAnyContinuation<Task<TResult>> (task, tasks);
1118 foreach (var t in tasks)
1119 t.ContinueWith (continuation);
1124 public static YieldAwaitable Yield ()
1126 return new YieldAwaitable ();
1130 internal static Task WhenAllCore (IList<Task> tasks)
1132 bool all_completed = true;
1133 foreach (var t in tasks) {
1135 throw new ArgumentException ("tasks", "the tasks argument contains a null element");
1137 all_completed &= t.Status == TaskStatus.RanToCompletion;
1141 return TaskConstants.Finished;
1143 var task = new Task (TaskActionInvoker.Empty, null, CancellationToken.None, TaskCreationOptions.None, null, TaskConstants.Finished);
1144 task.SetupScheduler (TaskScheduler.Current);
1146 var continuation = new WhenAllContinuation (task, tasks);
1147 foreach (var t in tasks)
1148 t.ContinueWith (continuation);
1153 internal static Task<Task> WhenAnyCore (IList<Task> tasks)
1155 if (tasks.Count == 0)
1156 throw new ArgumentException ("The tasks argument contains no tasks", "tasks");
1158 int completed_index = -1;
1159 for (int i = 0; i < tasks.Count; ++i) {
1162 throw new ArgumentException ("tasks", "the tasks argument contains a null element");
1164 if (t.IsCompleted && completed_index < 0)
1165 completed_index = i;
1168 var task = new Task<Task> (TaskActionInvoker.Empty, null, CancellationToken.None, TaskCreationOptions.None, null, TaskConstants.Finished);
1170 if (completed_index > 0) {
1171 task.TrySetResult (tasks[completed_index]);
1175 task.SetupScheduler (TaskScheduler.Current);
1177 var continuation = new WhenAnyContinuation<Task> (task, tasks);
1178 foreach (var t in tasks)
1179 t.ContinueWith (continuation);
1185 internal CancellationToken CancellationToken {
1191 public static TaskFactory Factory {
1193 return defaultFactory;
1197 public static int? CurrentId {
1200 return t == null ? (int?)null : t.Id;
1204 public AggregateException Exception {
1208 exSlot.Observed = true;
1209 return exSlot.Exception;
1213 public bool IsCanceled {
1215 return status == TaskStatus.Canceled;
1219 public bool IsCompleted {
1221 return status >= TaskStatus.RanToCompletion;
1225 public bool IsFaulted {
1227 return status == TaskStatus.Faulted;
1231 public TaskCreationOptions CreationOptions {
1233 return creationOptions & MaxTaskCreationOptions;
1237 public TaskStatus Status {
1243 Thread.MemoryBarrier ();
1247 TaskExceptionSlot ExceptionSlot {
1251 Interlocked.CompareExchange (ref exSlot, new TaskExceptionSlot (this), null);
1256 public object AsyncState {
1262 bool IAsyncResult.CompletedSynchronously {
1268 WaitHandle IAsyncResult.AsyncWaitHandle {
1280 bool IsContinuation {
1282 return contAncestor != null;
1286 internal Task ContinuationAncestor {
1288 return contAncestor;
1292 internal string DisplayActionMethod {
1294 Delegate d = invoker.Action;
1295 return d == null ? "<none>" : d.Method.ToString ();