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-2013 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 // parent is the outer task in which this task is created
52 // A reference to a Task on which this continuation is attached to
56 static readonly TaskFactory defaultFactory = new TaskFactory ();
58 CountdownEvent childTasks;
61 TaskCreationOptions creationOptions;
63 internal TaskScheduler scheduler;
65 TaskExceptionSlot exSlot;
66 ManualResetEvent wait_handle;
70 TaskActionInvoker invoker;
72 internal AtomicBooleanValue executing;
74 TaskCompletionQueue<IContinuation> continuations;
76 CancellationToken token;
77 CancellationTokenRegistration? cancellationRegistration;
79 internal const TaskCreationOptions WorkerTaskNotSupportedOptions = TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness;
81 const TaskCreationOptions MaxTaskCreationOptions =
83 TaskCreationOptions.DenyChildAttach | TaskCreationOptions.HideScheduler |
85 TaskCreationOptions.PreferFairness | TaskCreationOptions.LongRunning | TaskCreationOptions.AttachedToParent;
87 public Task (Action action)
88 : this (action, TaskCreationOptions.None)
93 public Task (Action action, TaskCreationOptions creationOptions)
94 : this (action, CancellationToken.None, creationOptions)
99 public Task (Action action, CancellationToken cancellationToken)
100 : this (action, cancellationToken, TaskCreationOptions.None)
105 public Task (Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
106 : this (TaskActionInvoker.Create (action), null, cancellationToken, creationOptions, current)
109 throw new ArgumentNullException ("action");
110 if (creationOptions > MaxTaskCreationOptions || creationOptions < TaskCreationOptions.None)
111 throw new ArgumentOutOfRangeException ("creationOptions");
114 public Task (Action<object> action, object state)
115 : this (action, state, TaskCreationOptions.None)
119 public Task (Action<object> action, object state, TaskCreationOptions creationOptions)
120 : this (action, state, CancellationToken.None, creationOptions)
124 public Task (Action<object> action, object state, CancellationToken cancellationToken)
125 : this (action, state, cancellationToken, TaskCreationOptions.None)
129 public Task (Action<object> action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
130 : this (TaskActionInvoker.Create (action), state, cancellationToken, creationOptions, current)
133 throw new ArgumentNullException ("action");
134 if (creationOptions > MaxTaskCreationOptions || creationOptions < TaskCreationOptions.None)
135 throw new ArgumentOutOfRangeException ("creationOptions");
138 internal Task (TaskActionInvoker invoker, object state, CancellationToken cancellationToken,
139 TaskCreationOptions creationOptions, Task parent = null, Task contAncestor = null, bool ignoreCancellation = false)
141 this.invoker = invoker;
142 this.creationOptions = creationOptions;
144 this.taskId = Interlocked.Increment (ref id);
145 this.token = cancellationToken;
146 this.parent = parent = parent == null ? current : parent;
147 this.contAncestor = contAncestor;
148 this.status = cancellationToken.IsCancellationRequested && !ignoreCancellation ? TaskStatus.Canceled : TaskStatus.Created;
150 // Process creationOptions
152 if (parent != null && HasFlag (creationOptions, TaskCreationOptions.AttachedToParent)
153 && !HasFlag (parent.CreationOptions, TaskCreationOptions.DenyChildAttach))
155 if (parent != null && HasFlag (creationOptions, TaskCreationOptions.AttachedToParent))
159 if (token.CanBeCanceled && !ignoreCancellation)
160 cancellationRegistration = token.Register (l => ((Task) l).CancelReal (), this);
163 static bool HasFlag (TaskCreationOptions opt, TaskCreationOptions member)
165 return (opt & member) == member;
171 Start (TaskScheduler.Current);
174 public void Start (TaskScheduler scheduler)
176 if (scheduler == null)
177 throw new ArgumentNullException ("scheduler");
179 if (status >= TaskStatus.WaitingToRun)
180 throw new InvalidOperationException ("The Task is not in a valid state to be started.");
183 throw new InvalidOperationException ("Start may not be called on a continuation task");
186 throw new InvalidOperationException ("Start may not be called on a promise-style task");
188 SetupScheduler (scheduler);
192 internal void SetupScheduler (TaskScheduler scheduler)
194 this.scheduler = scheduler;
195 Status = TaskStatus.WaitingForActivation;
198 public void RunSynchronously ()
200 RunSynchronously (TaskScheduler.Current);
203 public void RunSynchronously (TaskScheduler scheduler)
205 if (scheduler == null)
206 throw new ArgumentNullException ("scheduler");
208 if (Status > TaskStatus.WaitingForActivation)
209 throw new InvalidOperationException ("The task is not in a valid state to be started");
212 throw new InvalidOperationException ("RunSynchronously may not be called on a continuation task");
215 throw new InvalidOperationException ("RunSynchronously may not be called on a promise-style task");
217 RunSynchronouslyCore (scheduler);
220 internal void RunSynchronouslyCore (TaskScheduler scheduler)
222 SetupScheduler (scheduler);
223 Status = TaskStatus.WaitingToRun;
226 if (scheduler.RunInline (this, false))
228 } catch (Exception inner) {
229 throw new TaskSchedulerException (inner);
233 WaitCore (Timeout.Infinite, CancellationToken.None, false);
238 public Task ContinueWith (Action<Task> continuationAction)
240 return ContinueWith (continuationAction, TaskContinuationOptions.None);
243 public Task ContinueWith (Action<Task> continuationAction, TaskContinuationOptions continuationOptions)
245 return ContinueWith (continuationAction, CancellationToken.None, continuationOptions, TaskScheduler.Current);
248 public Task ContinueWith (Action<Task> continuationAction, CancellationToken cancellationToken)
250 return ContinueWith (continuationAction, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
253 public Task ContinueWith (Action<Task> continuationAction, TaskScheduler scheduler)
255 return ContinueWith (continuationAction, CancellationToken.None, TaskContinuationOptions.None, scheduler);
258 public Task ContinueWith (Action<Task> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
260 if (continuationAction == null)
261 throw new ArgumentNullException ("continuationAction");
262 if (scheduler == null)
263 throw new ArgumentNullException ("scheduler");
265 return ContinueWith (TaskActionInvoker.Create (continuationAction), cancellationToken, continuationOptions, scheduler);
268 internal Task ContinueWith (TaskActionInvoker invoker, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
270 var lazyCancellation = false;
272 lazyCancellation = (continuationOptions & TaskContinuationOptions.LazyCancellation) > 0;
274 var continuation = new Task (invoker, null, cancellationToken, GetCreationOptions (continuationOptions), null, this, lazyCancellation);
275 ContinueWithCore (continuation, continuationOptions, scheduler);
280 public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction)
282 return ContinueWith<TResult> (continuationFunction, TaskContinuationOptions.None);
285 public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, TaskContinuationOptions continuationOptions)
287 return ContinueWith<TResult> (continuationFunction, CancellationToken.None, continuationOptions, TaskScheduler.Current);
290 public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, CancellationToken cancellationToken)
292 return ContinueWith<TResult> (continuationFunction, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
295 public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, TaskScheduler scheduler)
297 return ContinueWith<TResult> (continuationFunction, CancellationToken.None, TaskContinuationOptions.None, scheduler);
300 public Task<TResult> ContinueWith<TResult> (Func<Task, TResult> continuationFunction, CancellationToken cancellationToken,
301 TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
303 if (continuationFunction == null)
304 throw new ArgumentNullException ("continuationFunction");
305 if (scheduler == null)
306 throw new ArgumentNullException ("scheduler");
308 return ContinueWith<TResult> (TaskActionInvoker.Create (continuationFunction), cancellationToken, continuationOptions, scheduler);
311 internal Task<TResult> ContinueWith<TResult> (TaskActionInvoker invoker, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
313 var lazyCancellation = false;
315 lazyCancellation = (continuationOptions & TaskContinuationOptions.LazyCancellation) > 0;
317 var continuation = new Task<TResult> (invoker, null, cancellationToken, GetCreationOptions (continuationOptions), parent, this, lazyCancellation);
318 ContinueWithCore (continuation, continuationOptions, scheduler);
323 internal void ContinueWithCore (Task continuation, TaskContinuationOptions options, TaskScheduler scheduler)
325 const TaskContinuationOptions wrongRan = TaskContinuationOptions.NotOnRanToCompletion | TaskContinuationOptions.OnlyOnRanToCompletion;
326 const TaskContinuationOptions wrongCanceled = TaskContinuationOptions.NotOnCanceled | TaskContinuationOptions.OnlyOnCanceled;
327 const TaskContinuationOptions wrongFaulted = TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.OnlyOnFaulted;
329 if (((options & wrongRan) == wrongRan) || ((options & wrongCanceled) == wrongCanceled) || ((options & wrongFaulted) == wrongFaulted))
330 throw new ArgumentException ("continuationOptions", "Some options are mutually exclusive");
332 // Already set the scheduler so that user can call Wait and that sort of stuff
333 continuation.scheduler = scheduler;
334 continuation.Status = TaskStatus.WaitingForActivation;
336 ContinueWith (new TaskContinuation (continuation, options));
339 internal bool ContinueWith (IContinuation continuation, bool canExecuteInline = true)
342 if (!canExecuteInline)
345 continuation.Execute ();
349 continuations.Add (continuation);
351 // Retry in case completion was achieved but event adding was too late
353 continuations.Remove (continuation);
354 if (!canExecuteInline)
357 continuation.Execute ();
363 internal void RemoveContinuation (IContinuation continuation)
365 continuations.Remove (continuation);
368 static internal TaskCreationOptions GetCreationOptions (TaskContinuationOptions kind)
370 TaskCreationOptions options = TaskCreationOptions.None;
371 if ((kind & TaskContinuationOptions.AttachedToParent) > 0)
372 options |= TaskCreationOptions.AttachedToParent;
373 if ((kind & TaskContinuationOptions.PreferFairness) > 0)
374 options |= TaskCreationOptions.PreferFairness;
375 if ((kind & TaskContinuationOptions.LongRunning) > 0)
376 options |= TaskCreationOptions.LongRunning;
382 #region Internal and protected thingies
383 internal void Schedule ()
385 Status = TaskStatus.WaitingToRun;
386 scheduler.QueueTask (this);
391 /* Allow scheduler to break fairness of deque ordering without
392 * breaking its semantic (the task can be executed twice but the
393 * second time it will return immediately
395 if (!executing.TryRelaxedSet ())
398 // Disable CancellationToken direct cancellation
399 if (cancellationRegistration != null) {
400 cancellationRegistration.Value.Dispose ();
401 cancellationRegistration = null;
404 // If Task are ran inline on the same thread we might trash these values
405 var saveCurrent = current;
406 var saveScheduler = TaskScheduler.Current;
410 TaskScheduler.Current = HasFlag (creationOptions, TaskCreationOptions.HideScheduler) ? TaskScheduler.Default : scheduler;
412 TaskScheduler.Current = scheduler;
415 if (!token.IsCancellationRequested) {
417 status = TaskStatus.Running;
421 } catch (OperationCanceledException oce) {
422 if (token != CancellationToken.None && oce.CancellationToken == token)
425 HandleGenericException (oce);
426 } catch (Exception e) {
427 HandleGenericException (e);
433 if (saveCurrent != null)
434 current = saveCurrent;
435 if (saveScheduler != null)
436 TaskScheduler.Current = saveScheduler;
440 internal bool TrySetCanceled ()
445 if (!executing.TryRelaxedSet ()) {
446 var sw = new SpinWait ();
457 internal bool TrySetException (AggregateException aggregate, bool cancellation)
462 if (!executing.TryRelaxedSet ()) {
463 var sw = new SpinWait ();
471 ExceptionSlot.Exception = aggregate;
472 Thread.MemoryBarrier ();
476 HandleGenericException (aggregate);
482 internal bool TrySetExceptionObserved ()
484 if (exSlot != null) {
485 exSlot.Observed = true;
491 internal void Execute ()
496 internal void AddChild ()
498 if (childTasks == null)
499 Interlocked.CompareExchange (ref childTasks, new CountdownEvent (1), null);
500 childTasks.AddCount ();
503 internal void ChildCompleted (AggregateException childEx)
505 if (childEx != null) {
506 if (ExceptionSlot.ChildExceptions == null)
507 Interlocked.CompareExchange (ref ExceptionSlot.ChildExceptions, new ConcurrentQueue<AggregateException> (), null);
508 ExceptionSlot.ChildExceptions.Enqueue (childEx);
511 if (childTasks.Signal () && status == TaskStatus.WaitingForChildrenToComplete) {
512 ProcessChildExceptions ();
513 Status = exSlot == null ? TaskStatus.RanToCompletion : TaskStatus.Faulted;
514 ProcessCompleteDelegates ();
515 if (parent != null &&
517 !HasFlag (parent.CreationOptions, TaskCreationOptions.DenyChildAttach) &&
519 HasFlag (creationOptions, TaskCreationOptions.AttachedToParent))
520 parent.ChildCompleted (this.Exception);
526 if (IsContinuation) {
527 var ancestor = contAncestor;
529 invoker.Invoke (ancestor, state, this);
531 invoker.Invoke (this, state, this);
535 internal void Finish ()
537 // If there was children created and they all finished, we set the countdown
538 if (childTasks != null) {
539 if (childTasks.Signal ())
540 ProcessChildExceptions (true);
543 // Don't override Canceled or Faulted
544 if (status == TaskStatus.Running) {
545 if (childTasks == null || childTasks.IsSet)
546 Status = TaskStatus.RanToCompletion;
548 Status = TaskStatus.WaitingForChildrenToComplete;
551 if (wait_handle != null)
554 // Tell parent that we are finished
555 if (parent != null && HasFlag (creationOptions, TaskCreationOptions.AttachedToParent) &&
557 !HasFlag (parent.CreationOptions, TaskCreationOptions.DenyChildAttach) &&
559 status != TaskStatus.WaitingForChildrenToComplete) {
560 parent.ChildCompleted (this.Exception);
563 // Completions are already processed when task is canceled or faulted
564 if (status == TaskStatus.RanToCompletion)
565 ProcessCompleteDelegates ();
567 // Reset the current thingies
570 if (TaskScheduler.Current == scheduler)
571 TaskScheduler.Current = null;
573 if (cancellationRegistration.HasValue)
574 cancellationRegistration.Value.Dispose ();
577 void ProcessCompleteDelegates ()
579 if (continuations.HasElements) {
580 IContinuation continuation;
581 while (continuations.TryGetNextCompletion (out continuation))
582 continuation.Execute ();
586 void ProcessChildExceptions (bool isParent = false)
588 if (exSlot == null || exSlot.ChildExceptions == null)
591 if (ExceptionSlot.Exception == null)
592 exSlot.Exception = new AggregateException ();
594 AggregateException childEx;
595 while (exSlot.ChildExceptions.TryDequeue (out childEx))
596 exSlot.Exception.AddChildException (childEx);
599 Status = TaskStatus.Faulted;
600 ProcessCompleteDelegates ();
605 #region Cancel and Wait related method
607 internal void CancelReal ()
609 Status = TaskStatus.Canceled;
611 if (wait_handle != null)
614 ProcessCompleteDelegates ();
617 void HandleGenericException (Exception e)
619 HandleGenericException (new AggregateException (e));
622 void HandleGenericException (AggregateException e)
624 ExceptionSlot.Exception = e;
625 Thread.MemoryBarrier ();
626 Status = TaskStatus.Faulted;
628 if (wait_handle != null)
631 ProcessCompleteDelegates ();
634 internal bool WaitOnChildren ()
636 if (Status == TaskStatus.WaitingForChildrenToComplete && childTasks != null) {
645 Wait (Timeout.Infinite, CancellationToken.None);
648 public void Wait (CancellationToken cancellationToken)
650 Wait (Timeout.Infinite, cancellationToken);
653 public bool Wait (TimeSpan timeout)
655 return Wait (CheckTimeout (timeout), CancellationToken.None);
658 public bool Wait (int millisecondsTimeout)
660 return Wait (millisecondsTimeout, CancellationToken.None);
663 public bool Wait (int millisecondsTimeout, CancellationToken cancellationToken)
665 if (millisecondsTimeout < -1)
666 throw new ArgumentOutOfRangeException ("millisecondsTimeout");
668 bool result = WaitCore (millisecondsTimeout, cancellationToken, true);
671 throw new AggregateException (new TaskCanceledException (this));
673 var exception = Exception;
674 if (exception != null)
680 internal bool WaitCore (int millisecondsTimeout, CancellationToken cancellationToken, bool runInline)
685 // If the task is ready to be run and we were supposed to wait on it indefinitely without cancellation, just run it
686 if (runInline && Status == TaskStatus.WaitingToRun && millisecondsTimeout == Timeout.Infinite && scheduler != null && !cancellationToken.CanBeCanceled)
687 scheduler.RunInline (this, true);
692 var continuation = new ManualResetContinuation ();
694 ContinueWith (continuation);
695 result = continuation.Event.Wait (millisecondsTimeout, cancellationToken);
698 RemoveContinuation (continuation);
699 continuation.Dispose ();
706 public static void WaitAll (params Task[] tasks)
708 WaitAll (tasks, Timeout.Infinite, CancellationToken.None);
711 public static void WaitAll (Task[] tasks, CancellationToken cancellationToken)
713 WaitAll (tasks, Timeout.Infinite, cancellationToken);
716 public static bool WaitAll (Task[] tasks, TimeSpan timeout)
718 return WaitAll (tasks, CheckTimeout (timeout), CancellationToken.None);
721 public static bool WaitAll (Task[] tasks, int millisecondsTimeout)
723 return WaitAll (tasks, millisecondsTimeout, CancellationToken.None);
726 public static bool WaitAll (Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
729 throw new ArgumentNullException ("tasks");
732 foreach (var t in tasks) {
734 throw new ArgumentException ("tasks", "the tasks argument contains a null element");
736 result &= t.Status == TaskStatus.RanToCompletion;
740 var continuation = new CountdownContinuation (tasks.Length);
742 foreach (var t in tasks)
743 t.ContinueWith (continuation);
745 result = continuation.Event.Wait (millisecondsTimeout, cancellationToken);
747 List<Exception> exceptions = null;
749 foreach (var t in tasks) {
751 if (t.Status == TaskStatus.RanToCompletion)
753 if (exceptions == null)
754 exceptions = new List<Exception> ();
755 if (t.Exception != null)
756 exceptions.AddRange (t.Exception.InnerExceptions);
758 exceptions.Add (new TaskCanceledException (t));
760 t.RemoveContinuation (continuation);
764 continuation.Dispose ();
766 if (exceptions != null)
767 throw new AggregateException (exceptions);
774 public static int WaitAny (params Task[] tasks)
776 return WaitAny (tasks, Timeout.Infinite, CancellationToken.None);
779 public static int WaitAny (Task[] tasks, TimeSpan timeout)
781 return WaitAny (tasks, CheckTimeout (timeout));
784 public static int WaitAny (Task[] tasks, int millisecondsTimeout)
786 return WaitAny (tasks, millisecondsTimeout, CancellationToken.None);
789 public static int WaitAny (Task[] tasks, CancellationToken cancellationToken)
791 return WaitAny (tasks, Timeout.Infinite, cancellationToken);
794 public static int WaitAny (Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
797 throw new ArgumentNullException ("tasks");
798 if (millisecondsTimeout < -1)
799 throw new ArgumentOutOfRangeException ("millisecondsTimeout");
800 CheckForNullTasks (tasks);
802 if (tasks.Length > 0) {
803 var continuation = new ManualResetContinuation ();
806 for (int i = 0; i < tasks.Length; i++) {
810 t.ContinueWith (continuation);
813 if (!(result = continuation.Event.Wait (millisecondsTimeout, cancellationToken)))
817 foreach (var t in tasks)
818 t.RemoveContinuation (continuation);
819 continuation.Dispose ();
823 int firstFinished = -1;
824 for (int i = 0; i < tasks.Length; i++) {
832 return firstFinished;
835 static int CheckTimeout (TimeSpan timeout)
838 return checked ((int)timeout.TotalMilliseconds);
839 } catch (System.OverflowException) {
840 throw new ArgumentOutOfRangeException ("timeout");
844 static void CheckForNullTasks (Task[] tasks)
846 foreach (var t in tasks)
848 throw new ArgumentException ("tasks", "the tasks argument contains a null element");
853 public void Dispose ()
858 protected virtual void Dispose (bool disposing)
861 throw new InvalidOperationException ("A task may only be disposed if it is in a completion state");
863 // Set action to null so that the GC can collect the delegate and thus
864 // any big object references that the user might have captured in a anonymous method
868 if (cancellationRegistration != null)
869 cancellationRegistration.Value.Dispose ();
870 if (wait_handle != null)
871 wait_handle.Dispose ();
881 Task ContinueWith (Action<Task, object> continuationAction, object state, CancellationToken cancellationToken,
882 TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
884 if (continuationAction == null)
885 throw new ArgumentNullException ("continuationAction");
886 if (scheduler == null)
887 throw new ArgumentNullException ("scheduler");
889 Task continuation = new Task (TaskActionInvoker.Create (continuationAction),
890 state, cancellationToken,
891 GetCreationOptions (continuationOptions),
894 ContinueWithCore (continuation, continuationOptions, scheduler);
901 public ConfiguredTaskAwaitable ConfigureAwait (bool continueOnCapturedContext)
903 return new ConfiguredTaskAwaitable (this, continueOnCapturedContext);
906 public Task ContinueWith (Action<Task, object> continuationAction, object state)
908 return ContinueWith (continuationAction, state, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Current);
911 public Task ContinueWith (Action<Task, object> continuationAction, object state, CancellationToken cancellationToken)
913 return ContinueWith (continuationAction, state, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
916 public Task ContinueWith (Action<Task, object> continuationAction, object state, TaskContinuationOptions continuationOptions)
918 return ContinueWith (continuationAction, state, CancellationToken.None, continuationOptions, TaskScheduler.Current);
921 public Task ContinueWith (Action<Task, object> continuationAction, object state, TaskScheduler scheduler)
923 return ContinueWith (continuationAction, state, CancellationToken.None, TaskContinuationOptions.None, scheduler);
926 public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state)
928 return ContinueWith<TResult> (continuationFunction, state, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Current);
931 public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state, TaskContinuationOptions continuationOptions)
933 return ContinueWith<TResult> (continuationFunction, state, CancellationToken.None, continuationOptions, TaskScheduler.Current);
936 public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state, CancellationToken cancellationToken)
938 return ContinueWith<TResult> (continuationFunction, state, cancellationToken, TaskContinuationOptions.None, TaskScheduler.Current);
941 public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state, TaskScheduler scheduler)
943 return ContinueWith<TResult> (continuationFunction, state, CancellationToken.None, TaskContinuationOptions.None, scheduler);
946 public Task<TResult> ContinueWith<TResult> (Func<Task, object, TResult> continuationFunction, object state, CancellationToken cancellationToken,
947 TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
949 if (continuationFunction == null)
950 throw new ArgumentNullException ("continuationFunction");
951 if (scheduler == null)
952 throw new ArgumentNullException ("scheduler");
954 var t = new Task<TResult> (TaskActionInvoker.Create (continuationFunction),
957 GetCreationOptions (continuationOptions),
961 ContinueWithCore (t, continuationOptions, scheduler);
966 public static Task Delay (int millisecondsDelay)
968 return Delay (millisecondsDelay, CancellationToken.None);
971 public static Task Delay (TimeSpan delay)
973 return Delay (CheckTimeout (delay), CancellationToken.None);
976 public static Task Delay (TimeSpan delay, CancellationToken cancellationToken)
978 return Delay (CheckTimeout (delay), cancellationToken);
981 public static Task Delay (int millisecondsDelay, CancellationToken cancellationToken)
983 if (millisecondsDelay < -1)
984 throw new ArgumentOutOfRangeException ("millisecondsDelay");
986 if (cancellationToken.IsCancellationRequested)
987 return TaskConstants.Canceled;
989 var task = new Task (TaskActionInvoker.Empty, null, cancellationToken, TaskCreationOptions.None, null, null);
990 task.SetupScheduler (TaskScheduler.Default);
992 if (millisecondsDelay != Timeout.Infinite) {
993 var timer = new Timer (delegate (object state) {
994 var t = (Task) state;
995 if (t.Status == TaskStatus.WaitingForActivation) {
996 t.Status = TaskStatus.Running;
999 }, task, millisecondsDelay, -1);
1001 task.ContinueWith (new DisposeContinuation (timer));
1007 public static Task<TResult> FromResult<TResult> (TResult result)
1009 var tcs = new TaskCompletionSource<TResult> ();
1010 tcs.SetResult (result);
1014 public TaskAwaiter GetAwaiter ()
1016 return new TaskAwaiter (this);
1019 public static Task Run (Action action)
1021 return Run (action, CancellationToken.None);
1024 public static Task Run (Action action, CancellationToken cancellationToken)
1026 if (cancellationToken.IsCancellationRequested)
1027 return TaskConstants.Canceled;
1029 return Task.Factory.StartNew (action, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
1032 public static Task Run (Func<Task> function)
1034 return Run (function, CancellationToken.None);
1037 public static Task Run (Func<Task> function, CancellationToken cancellationToken)
1039 if (cancellationToken.IsCancellationRequested)
1040 return TaskConstants.Canceled;
1042 return TaskExtensionsImpl.Unwrap (Task.Factory.StartNew (function, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default));
1045 public static Task<TResult> Run<TResult> (Func<TResult> function)
1047 return Run (function, CancellationToken.None);
1050 public static Task<TResult> Run<TResult> (Func<TResult> function, CancellationToken cancellationToken)
1052 if (cancellationToken.IsCancellationRequested)
1053 return TaskConstants<TResult>.Canceled;
1055 return Task.Factory.StartNew (function, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
1058 public static Task<TResult> Run<TResult> (Func<Task<TResult>> function)
1060 return Run (function, CancellationToken.None);
1063 public static Task<TResult> Run<TResult> (Func<Task<TResult>> function, CancellationToken cancellationToken)
1065 if (cancellationToken.IsCancellationRequested)
1066 return TaskConstants<TResult>.Canceled;
1068 return TaskExtensionsImpl.Unwrap (Task.Factory.StartNew (function, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default));
1071 public static Task WhenAll (params Task[] tasks)
1074 throw new ArgumentNullException ("tasks");
1076 return WhenAllCore (tasks);
1079 public static Task WhenAll (IEnumerable<Task> tasks)
1082 throw new ArgumentNullException ("tasks");
1084 // Call ToList on input enumeration or we end up
1085 // enumerating it more than once
1086 return WhenAllCore (new List<Task> (tasks));
1089 public static Task<TResult[]> WhenAll<TResult> (params Task<TResult>[] tasks)
1092 throw new ArgumentNullException ("tasks");
1094 return WhenAllCore<TResult> (tasks);
1097 public static Task<TResult[]> WhenAll<TResult> (IEnumerable<Task<TResult>> tasks)
1100 throw new ArgumentNullException ("tasks");
1102 // Call ToList on input enumeration or we end up
1103 // enumerating it more than once
1104 return WhenAllCore<TResult> (new List<Task<TResult>> (tasks));
1107 internal static Task<TResult[]> WhenAllCore<TResult> (IList<Task<TResult>> tasks)
1109 if (tasks.Count == 0)
1110 return FromResult(new TResult[0]);
1112 foreach (var t in tasks) {
1114 throw new ArgumentException ("tasks", "the tasks argument contains a null element");
1117 var task = new Task<TResult[]> (TaskActionInvoker.Empty, null, CancellationToken.None, TaskCreationOptions.None, null, TaskConstants.Finished);
1118 task.SetupScheduler (TaskScheduler.Current);
1120 var continuation = new WhenAllContinuation<TResult> (task, tasks);
1121 foreach (var t in tasks)
1122 t.ContinueWith (continuation);
1127 public static Task<Task> WhenAny (params Task[] tasks)
1130 throw new ArgumentNullException ("tasks");
1132 return WhenAnyCore (tasks);
1135 public static Task<Task> WhenAny (IEnumerable<Task> tasks)
1138 throw new ArgumentNullException ("tasks");
1140 return WhenAnyCore (new List<Task> (tasks));
1143 public static Task<Task<TResult>> WhenAny<TResult> (params Task<TResult>[] tasks)
1146 throw new ArgumentNullException ("tasks");
1148 return WhenAnyCore<TResult> (tasks);
1151 public static Task<Task<TResult>> WhenAny<TResult> (IEnumerable<Task<TResult>> tasks)
1154 throw new ArgumentNullException ("tasks");
1156 return WhenAnyCore<TResult> (new List<Task<TResult>> (tasks));
1159 static Task<Task<TResult>> WhenAnyCore<TResult> (IList<Task<TResult>> tasks)
1161 if (tasks.Count == 0)
1162 throw new ArgumentException ("The tasks argument contains no tasks", "tasks");
1164 int completed_index = -1;
1165 for (int i = 0; i < tasks.Count; ++i) {
1168 throw new ArgumentException ("tasks", "the tasks argument contains a null element");
1170 if (t.IsCompleted && completed_index < 0)
1171 completed_index = i;
1174 var task = new Task<Task<TResult>> (TaskActionInvoker.Empty, null, CancellationToken.None, TaskCreationOptions.None, null, TaskConstants.Finished);
1176 if (completed_index > 0) {
1177 task.TrySetResult (tasks[completed_index]);
1181 task.SetupScheduler (TaskScheduler.Current);
1183 var continuation = new WhenAnyContinuation<Task<TResult>> (task, tasks);
1184 foreach (var t in tasks)
1185 t.ContinueWith (continuation);
1190 public static YieldAwaitable Yield ()
1192 return new YieldAwaitable ();
1196 internal static Task WhenAllCore (IList<Task> tasks)
1198 bool all_completed = true;
1199 foreach (var t in tasks) {
1201 throw new ArgumentException ("tasks", "the tasks argument contains a null element");
1203 all_completed &= t.Status == TaskStatus.RanToCompletion;
1207 return TaskConstants.Finished;
1209 var task = new Task (TaskActionInvoker.Empty, null, CancellationToken.None, TaskCreationOptions.None, null, TaskConstants.Finished);
1210 task.SetupScheduler (TaskScheduler.Current);
1212 var continuation = new WhenAllContinuation (task, tasks);
1213 foreach (var t in tasks)
1214 t.ContinueWith (continuation);
1219 internal static Task<Task> WhenAnyCore (IList<Task> tasks)
1221 if (tasks.Count == 0)
1222 throw new ArgumentException ("The tasks argument contains no tasks", "tasks");
1224 int completed_index = -1;
1225 for (int i = 0; i < tasks.Count; ++i) {
1228 throw new ArgumentException ("tasks", "the tasks argument contains a null element");
1230 if (t.IsCompleted && completed_index < 0)
1231 completed_index = i;
1234 var task = new Task<Task> (TaskActionInvoker.Empty, null, CancellationToken.None, TaskCreationOptions.None, null, TaskConstants.Finished);
1236 if (completed_index > 0) {
1237 task.TrySetResult (tasks[completed_index]);
1241 task.SetupScheduler (TaskScheduler.Current);
1243 var continuation = new WhenAnyContinuation<Task> (task, tasks);
1244 foreach (var t in tasks)
1245 t.ContinueWith (continuation);
1251 internal CancellationToken CancellationToken {
1257 public static TaskFactory Factory {
1259 return defaultFactory;
1263 public static int? CurrentId {
1266 return t == null ? (int?)null : t.Id;
1270 public AggregateException Exception {
1272 if (exSlot == null || !IsFaulted)
1274 exSlot.Observed = true;
1275 return exSlot.Exception;
1279 public bool IsCanceled {
1281 return status == TaskStatus.Canceled;
1285 public bool IsCompleted {
1287 return status >= TaskStatus.RanToCompletion;
1291 public bool IsFaulted {
1293 return status == TaskStatus.Faulted;
1297 public TaskCreationOptions CreationOptions {
1299 return creationOptions & MaxTaskCreationOptions;
1303 public TaskStatus Status {
1309 Thread.MemoryBarrier ();
1313 internal TaskExceptionSlot ExceptionSlot {
1317 Interlocked.CompareExchange (ref exSlot, new TaskExceptionSlot (this), null);
1322 public object AsyncState {
1328 bool IAsyncResult.CompletedSynchronously {
1334 WaitHandle IAsyncResult.AsyncWaitHandle {
1336 if (invoker == null)
1337 throw new ObjectDisposedException (GetType ().ToString ());
1339 if (wait_handle == null)
1340 Interlocked.CompareExchange (ref wait_handle, new ManualResetEvent (IsCompleted), null);
1352 bool IsContinuation {
1354 return contAncestor != null;
1360 return invoker == TaskActionInvoker.Promise;
1364 internal Task ContinuationAncestor {
1366 return contAncestor;
1370 internal string DisplayActionMethod {
1372 Delegate d = invoker.Action;
1373 return d == null ? "<none>" : d.Method.ToString ();