Task.ContinueWith Method

Definition

Creates a continuation that executes asynchronously when the target Task completes.

Overloads

ContinueWith(Action<Task,Object>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler)

Creates a continuation that receives caller-supplied state information and a cancellation token and that executes when the target Task completes. The continuation executes based on a set of specified conditions and uses a specified scheduler.

ContinueWith(Action<Task>, CancellationToken, TaskContinuationOptions, TaskScheduler)

Creates a continuation that executes when the target task competes according to the specified TaskContinuationOptions. The continuation receives a cancellation token and uses a specified scheduler.

ContinueWith(Action<Task,Object>, Object, TaskScheduler)

Creates a continuation that receives caller-supplied state information and executes asynchronously when the target Task completes. The continuation uses a specified scheduler.

ContinueWith(Action<Task,Object>, Object, TaskContinuationOptions)

Creates a continuation that receives caller-supplied state information and executes when the target Task completes. The continuation executes based on a set of specified conditions.

ContinueWith(Action<Task,Object>, Object, CancellationToken)

Creates a continuation that receives caller-supplied state information and a cancellation token and that executes asynchronously when the target Task completes.

ContinueWith(Action<Task>)

Creates a continuation that executes asynchronously when the target Task completes.

ContinueWith(Action<Task>, TaskContinuationOptions)

Creates a continuation that executes when the target task completes according to the specified TaskContinuationOptions.

ContinueWith(Action<Task>, CancellationToken)

Creates a continuation that receives a cancellation token and executes asynchronously when the target Task completes.

ContinueWith(Action<Task,Object>, Object)

Creates a continuation that receives caller-supplied state information and executes when the target Task completes.

ContinueWith(Action<Task>, TaskScheduler)

Creates a continuation that executes asynchronously when the target Task completes. The continuation uses a specified scheduler.

ContinueWith<TResult>(Func<Task,Object,TResult>, Object, TaskScheduler)

Creates a continuation that executes asynchronously when the target Task completes. The continuation receives caller-supplied state information and uses a specified scheduler.

ContinueWith<TResult>(Func<Task,Object,TResult>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler)

Creates a continuation that executes based on the specified task continuation options when the target Task completes and returns a value. The continuation receives caller-supplied state information and a cancellation token and uses the specified scheduler.

ContinueWith<TResult>(Func<Task,TResult>, CancellationToken, TaskContinuationOptions, TaskScheduler)

Creates a continuation that executes according to the specified continuation options and returns a value. The continuation is passed a cancellation token and uses a specified scheduler.

ContinueWith<TResult>(Func<Task,Object,TResult>, Object, CancellationToken)

Creates a continuation that executes asynchronously when the target Task completes and returns a value. The continuation receives caller-supplied state information and a cancellation token.

ContinueWith<TResult>(Func<Task,Object,TResult>, Object, TaskContinuationOptions)

Creates a continuation that executes based on the specified task continuation options when the target Task completes. The continuation receives caller-supplied state information.

ContinueWith<TResult>(Func<Task,TResult>, TaskContinuationOptions)

Creates a continuation that executes according to the specified continuation options and returns a value.

ContinueWith<TResult>(Func<Task,TResult>, TaskScheduler)

Creates a continuation that executes asynchronously when the target Task completes and returns a value. The continuation uses a specified scheduler.

ContinueWith<TResult>(Func<Task,TResult>, CancellationToken)

Creates a continuation that executes asynchronously when the target Task completes and returns a value. The continuation receives a cancellation token.

ContinueWith<TResult>(Func<Task,Object,TResult>, Object)

Creates a continuation that receives caller-supplied state information and executes asynchronously when the target Task completes and returns a value.

ContinueWith<TResult>(Func<Task,TResult>)

Creates a continuation that executes asynchronously when the target Task<TResult> completes and returns a value.

ContinueWith(Action<Task,Object>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Creates a continuation that receives caller-supplied state information and a cancellation token and that executes when the target Task completes. The continuation executes based on a set of specified conditions and uses a specified scheduler.

C#
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task,object> continuationAction, object state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskContinuationOptions continuationOptions, System.Threading.Tasks.TaskScheduler scheduler);
C#
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task,object?> continuationAction, object? state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskContinuationOptions continuationOptions, System.Threading.Tasks.TaskScheduler scheduler);

Parameters

continuationAction
Action<Task,Object>

An action to run when the Task completes. When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.

state
Object

An object representing data to be used by the continuation action.

cancellationToken
CancellationToken

The CancellationToken that will be assigned to the new continuation task.

continuationOptions
TaskContinuationOptions

Options for when the continuation is scheduled and how it behaves. This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.

scheduler
TaskScheduler

The TaskScheduler to associate with the continuation task and to use for its execution.

Returns

A new continuation Task.

Exceptions

The scheduler argument is null.

The continuationOptions argument specifies an invalid value for TaskContinuationOptions.

The provided CancellationToken has already been disposed.

Remarks

The returned Task will not be scheduled for execution until the current task has completed. If the criteria specified through the continuationOptions parameter are not met, the continuation task will be canceled instead of scheduled.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

ContinueWith(Action<Task>, CancellationToken, TaskContinuationOptions, TaskScheduler)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Creates a continuation that executes when the target task competes according to the specified TaskContinuationOptions. The continuation receives a cancellation token and uses a specified scheduler.

C#
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task> continuationAction, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskContinuationOptions continuationOptions, System.Threading.Tasks.TaskScheduler scheduler);

Parameters

continuationAction
Action<Task>

An action to run according to the specified continuationOptions. When run, the delegate will be passed the completed task as an argument.

cancellationToken
CancellationToken

The CancellationToken that will be assigned to the new continuation task.

continuationOptions
TaskContinuationOptions

Options for when the continuation is scheduled and how it behaves. This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.

scheduler
TaskScheduler

The TaskScheduler to associate with the continuation task and to use for its execution.

Returns

A new continuation Task.

Exceptions

The CancellationTokenSource that created the token has already been disposed.

The continuationAction argument is null.

-or-

The scheduler argument is null.

The continuationOptions argument specifies an invalid value for TaskContinuationOptions.

Examples

The following is an example of using ContinueWith to run work both in the background and on the user interface threads.

C#
private void Button1_Click(object sender, EventArgs e)
{
   var backgroundScheduler = TaskScheduler.Default;
   var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
   Task.Factory.StartNew(delegate { DoBackgroundComputation(); },
                         backgroundScheduler).
   ContinueWith(delegate { UpdateUI(); }, uiScheduler).
                ContinueWith(delegate { DoAnotherBackgroundComputation(); },
                             backgroundScheduler).
                ContinueWith(delegate { UpdateUIAgain(); }, uiScheduler);
}

Remarks

The returned Task will not be scheduled for execution until the current task has completed. If the criteria specified through the continuationOptions parameter are not met, the continuation task will be canceled instead of scheduled.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

ContinueWith(Action<Task,Object>, Object, TaskScheduler)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Creates a continuation that receives caller-supplied state information and executes asynchronously when the target Task completes. The continuation uses a specified scheduler.

C#
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task,object> continuationAction, object state, System.Threading.Tasks.TaskScheduler scheduler);
C#
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task,object?> continuationAction, object? state, System.Threading.Tasks.TaskScheduler scheduler);

Parameters

continuationAction
Action<Task,Object>

An action to run when the Task completes. When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.

state
Object

An object representing data to be used by the continuation action.

scheduler
TaskScheduler

The TaskScheduler to associate with the continuation task and to use for its execution.

Returns

A new continuation Task.

Exceptions

The scheduler argument is null.

Remarks

The returned Task will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

ContinueWith(Action<Task,Object>, Object, TaskContinuationOptions)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Creates a continuation that receives caller-supplied state information and executes when the target Task completes. The continuation executes based on a set of specified conditions.

C#
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task,object> continuationAction, object state, System.Threading.Tasks.TaskContinuationOptions continuationOptions);
C#
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task,object?> continuationAction, object? state, System.Threading.Tasks.TaskContinuationOptions continuationOptions);

Parameters

continuationAction
Action<Task,Object>

An action to run when the Task completes. When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.

state
Object

An object representing data to be used by the continuation action.

continuationOptions
TaskContinuationOptions

Options for when the continuation is scheduled and how it behaves. This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.

Returns

A new continuation Task.

Exceptions

The continuationAction argument is null.

The continuationOptions argument specifies an invalid value for TaskContinuationOptions.

Remarks

The returned Task will not be scheduled for execution until the current task has completed. If the continuation criteria specified through the continuationOptions parameter are not met, the continuation task will be canceled instead of scheduled.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

ContinueWith(Action<Task,Object>, Object, CancellationToken)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Creates a continuation that receives caller-supplied state information and a cancellation token and that executes asynchronously when the target Task completes.

C#
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task,object> continuationAction, object state, System.Threading.CancellationToken cancellationToken);
C#
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task,object?> continuationAction, object? state, System.Threading.CancellationToken cancellationToken);

Parameters

continuationAction
Action<Task,Object>

An action to run when the Task completes. When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.

state
Object

An object representing data to be used by the continuation action.

cancellationToken
CancellationToken

The CancellationToken that will be assigned to the new continuation task.

Returns

A new continuation Task.

Exceptions

The continuationAction argument is null.

The provided CancellationToken has already been disposed.

Remarks

The returned Task will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

ContinueWith(Action<Task>)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Creates a continuation that executes asynchronously when the target Task completes.

C#
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task> continuationAction);

Parameters

continuationAction
Action<Task>

An action to run when the Task completes. When run, the delegate will be passed the completed task as an argument.

Returns

A new continuation Task.

Exceptions

The continuationAction argument is null.

Examples

The following example defines a task that populates an array with 100 random date and time values. It uses the ContinueWith(Action<Task>) method to select the earliest and the latest date values once the array is fully populated.

C#
using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var firstTask = Task.Factory.StartNew( () => {
                               Random rnd = new Random();
                               DateTime[] dates = new DateTime[100];
                               Byte[] buffer = new Byte[8];
                               int ctr = dates.GetLowerBound(0);
                               while (ctr <= dates.GetUpperBound(0)) {
                                  rnd.NextBytes(buffer);
                                  long ticks = BitConverter.ToInt64(buffer, 0);
                                  if (ticks <= DateTime.MinValue.Ticks | ticks >= DateTime.MaxValue.Ticks)
                                     continue;

                                  dates[ctr] = new DateTime(ticks);
                                  ctr++;
                               }
                               return dates;
                            } ); 
                         
      Task continuationTask = firstTask.ContinueWith( (antecedent) => {
                             DateTime[] dates = antecedent.Result;
                             DateTime earliest = dates[0];
                             DateTime latest = earliest;
                             
                             for (int ctr = dates.GetLowerBound(0) + 1; ctr <= dates.GetUpperBound(0); ctr++) {
                                if (dates[ctr] < earliest) earliest = dates[ctr];
                                if (dates[ctr] > latest) latest = dates[ctr];
                             }
                             Console.WriteLine("Earliest date: {0}", earliest);
                             Console.WriteLine("Latest date: {0}", latest);
                          } );                      
      // Since a console application otherwise terminates, wait for the continuation to complete.
     continuationTask.Wait();
   }
}
// The example displays output like the following:
//       Earliest date: 2/11/0110 12:03:41 PM
//       Latest date: 7/29/9989 2:14:49 PM

Because a console application may terminate before the continuation task executes, the Wait() method is called to ensure that the continuation finishes executing before the example ends.

For an additional example, see Chaining Tasks by Using Continuation Tasks.

Remarks

The returned Task will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

ContinueWith(Action<Task>, TaskContinuationOptions)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Creates a continuation that executes when the target task completes according to the specified TaskContinuationOptions.

C#
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task> continuationAction, System.Threading.Tasks.TaskContinuationOptions continuationOptions);

Parameters

continuationAction
Action<Task>

An action to run according to the specified continuationOptions. When run, the delegate will be passed the completed task as an argument.

continuationOptions
TaskContinuationOptions

Options for when the continuation is scheduled and how it behaves. This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.

Returns

A new continuation Task.

Exceptions

The continuationAction argument is null.

The continuationOptions argument specifies an invalid value for TaskContinuationOptions.

Examples

The following example demonstrates using TaskContinuationOptions to specify that a continuation task should run synchronously when the antecedent task completes. (If the specified task has already completed by the time ContinueWith is called, the synchronous continuation will run on the thread calling ContinueWith.)

C#
public class TaskCounter
{
   private volatile int _count;

   public void Track(Task t)
   {
      if (t == null) throw new ArgumentNullException("t");
      Interlocked.Increment(ref _count);
      t.ContinueWith(ct => Interlocked.Decrement(ref _count), TaskContinuationOptions.ExecuteSynchronously);
   }

   public int NumberOfActiveTasks { get { return _count; } }
}

Remarks

The returned Task will not be scheduled for execution until the current task has completed. If the continuation criteria specified through the continuationOptions parameter are not met, the continuation task will be canceled instead of scheduled.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

ContinueWith(Action<Task>, CancellationToken)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Creates a continuation that receives a cancellation token and executes asynchronously when the target Task completes.

C#
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task> continuationAction, System.Threading.CancellationToken cancellationToken);

Parameters

continuationAction
Action<Task>

An action to run when the Task completes. When run, the delegate will be passed the completed task as an argument.

cancellationToken
CancellationToken

The CancellationToken that will be assigned to the new continuation task.

Returns

A new continuation Task.

Exceptions

The CancellationTokenSource that created the token has already been disposed.

The continuationAction argument is null.

Remarks

The returned Task will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

ContinueWith(Action<Task,Object>, Object)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Creates a continuation that receives caller-supplied state information and executes when the target Task completes.

C#
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task,object> continuationAction, object state);
C#
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task,object?> continuationAction, object? state);

Parameters

continuationAction
Action<Task,Object>

An action to run when the task completes. When run, the delegate is passed the completed task and a caller-supplied state object as arguments.

state
Object

An object representing data to be used by the continuation action.

Returns

A new continuation task.

Exceptions

The continuationAction argument is null.

Remarks

The returned Task will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting early due to cancellation.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

ContinueWith(Action<Task>, TaskScheduler)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Creates a continuation that executes asynchronously when the target Task completes. The continuation uses a specified scheduler.

C#
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task> continuationAction, System.Threading.Tasks.TaskScheduler scheduler);

Parameters

continuationAction
Action<Task>

An action to run when the Task completes. When run, the delegate will be passed the completed task as an argument.

scheduler
TaskScheduler

The TaskScheduler to associate with the continuation task and to use for its execution.

Returns

A new continuation Task.

Exceptions

The Task has been disposed.

The continuationAction argument is null.

-or-

The scheduler argument is null.

Remarks

The returned Task will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

ContinueWith<TResult>(Func<Task,Object,TResult>, Object, TaskScheduler)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Creates a continuation that executes asynchronously when the target Task completes. The continuation receives caller-supplied state information and uses a specified scheduler.

C#
public System.Threading.Tasks.Task<TResult> ContinueWith<TResult> (Func<System.Threading.Tasks.Task,object,TResult> continuationFunction, object state, System.Threading.Tasks.TaskScheduler scheduler);
C#
public System.Threading.Tasks.Task<TResult> ContinueWith<TResult> (Func<System.Threading.Tasks.Task,object?,TResult> continuationFunction, object? state, System.Threading.Tasks.TaskScheduler scheduler);

Type Parameters

TResult

The type of the result produced by the continuation.

Parameters

continuationFunction
Func<Task,Object,TResult>

A function to run when the Task completes. When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.

state
Object

An object representing data to be used by the continuation function.

scheduler
TaskScheduler

The TaskScheduler to associate with the continuation task and to use for its execution.

Returns

A new continuation Task<TResult>.

Exceptions

The scheduler argument is null.

Remarks

The returned Task<TResult> will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

ContinueWith<TResult>(Func<Task,Object,TResult>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Creates a continuation that executes based on the specified task continuation options when the target Task completes and returns a value. The continuation receives caller-supplied state information and a cancellation token and uses the specified scheduler.

C#
public System.Threading.Tasks.Task<TResult> ContinueWith<TResult> (Func<System.Threading.Tasks.Task,object,TResult> continuationFunction, object state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskContinuationOptions continuationOptions, System.Threading.Tasks.TaskScheduler scheduler);
C#
public System.Threading.Tasks.Task<TResult> ContinueWith<TResult> (Func<System.Threading.Tasks.Task,object?,TResult> continuationFunction, object? state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskContinuationOptions continuationOptions, System.Threading.Tasks.TaskScheduler scheduler);

Type Parameters

TResult

The type of the result produced by the continuation.

Parameters

continuationFunction
Func<Task,Object,TResult>

A function to run when the Task completes. When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.

state
Object

An object representing data to be used by the continuation function.

cancellationToken
CancellationToken

The CancellationToken that will be assigned to the new continuation task.

continuationOptions
TaskContinuationOptions

Options for when the continuation is scheduled and how it behaves. This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.

scheduler
TaskScheduler

The TaskScheduler to associate with the continuation task and to use for its execution.

Returns

A new continuation Task<TResult>.

Exceptions

The scheduler argument is null.

The continuationOptions argument specifies an invalid value for TaskContinuationOptions.

The provided CancellationToken has already been disposed.

Remarks

The returned Task<TResult> will not be scheduled for execution until the current task has completed. If the criteria specified through the continuationOptions parameter are not met, the continuation task will be canceled instead of scheduled.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

ContinueWith<TResult>(Func<Task,TResult>, CancellationToken, TaskContinuationOptions, TaskScheduler)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Creates a continuation that executes according to the specified continuation options and returns a value. The continuation is passed a cancellation token and uses a specified scheduler.

C#
public System.Threading.Tasks.Task<TResult> ContinueWith<TResult> (Func<System.Threading.Tasks.Task,TResult> continuationFunction, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskContinuationOptions continuationOptions, System.Threading.Tasks.TaskScheduler scheduler);

Type Parameters

TResult

The type of the result produced by the continuation.

Parameters

continuationFunction
Func<Task,TResult>

A function to run according to the specified continuationOptions. When run, the delegate will be passed the completed task as an argument.

cancellationToken
CancellationToken

The CancellationToken that will be assigned to the new continuation task.

continuationOptions
TaskContinuationOptions

Options for when the continuation is scheduled and how it behaves. This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.

scheduler
TaskScheduler

The TaskScheduler to associate with the continuation task and to use for its execution.

Returns

A new continuation Task<TResult>.

Exceptions

The Task has been disposed.

-or-

The CancellationTokenSource that created the token has already been disposed.

The continuationFunction argument is null.

-or-

The scheduler argument is null.

The continuationOptions argument specifies an invalid value for TaskContinuationOptions.

Examples

The following example shows how to use the ContinueWith method with continuation options:

C#
using System;
using System.Threading;
using System.Threading.Tasks;

class ContinuationOptionsDemo
{
    // Demonstrated features:
    //      TaskContinuationOptions
    //		Task.ContinueWith()
    // 		Task.Factory
    //		Task.Wait()
    // Expected results:
    // 		This sample demonstrates branched continuation sequences - Task+Commit or Task+Rollback.
    //      Notice that no if statements are used.
    //		The first sequence is successful - tran1 and commitTran1 are executed. rollbackTran1 is canceled.
    //		The second sequence is unsuccessful - tran2 and rollbackTran2 are executed. tran2 is faulted, and commitTran2 is canceled.
    // Documentation:
    //		http://msdn.microsoft.com/library/system.threading.tasks.taskcontinuationoptions(VS.100).aspx
    static void Main()
    {
        Action success = () => Console.WriteLine("Task={0}, Thread={1}: Begin successful transaction",
                                                Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
        Action failure = () =>
        {
            Console.WriteLine("Task={0}, Thread={1}: Begin transaction and encounter an error",
                                Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
            throw new InvalidOperationException("SIMULATED EXCEPTION");
        };

        Action<Task> commit = (antecendent) => Console.WriteLine("Task={0}, Thread={1}: Commit transaction",
                                                                Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
        Action<Task> rollback = (antecendent) =>
        {
            // "Observe" your antecedent's exception so as to avoid an exception
            // being thrown on the finalizer thread
            var unused = antecendent.Exception;

            Console.WriteLine("Task={0}, Thread={1}: Rollback transaction",
                  Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
        };

        // Successful transaction - Begin + Commit
        Console.WriteLine("Demonstrating a successful transaction");

        // Initial task
        // Treated as "fire-and-forget" -- any exceptions will be cleaned up in rollback continuation
        Task tran1 = Task.Factory.StartNew(success);

        // The following task gets scheduled only if tran1 completes successfully
        var commitTran1 = tran1.ContinueWith(commit, TaskContinuationOptions.OnlyOnRanToCompletion);

        // The following task gets scheduled only if tran1 DOES NOT complete successfully
        var rollbackTran1 = tran1.ContinueWith(rollback, TaskContinuationOptions.NotOnRanToCompletion);

        // For demo purposes, wait for the sample to complete
        commitTran1.Wait();

        // -----------------------------------------------------------------------------------

        // Failed transaction - Begin + exception + Rollback
        Console.WriteLine("\nDemonstrating a failed transaction");

        // Initial task
        // Treated as "fire-and-forget" -- any exceptions will be cleaned up in rollback continuation
        Task tran2 = Task.Factory.StartNew(failure);

        // The following task gets scheduled only if tran2 completes successfully
        var commitTran2 = tran2.ContinueWith(commit, TaskContinuationOptions.OnlyOnRanToCompletion);

        // The following task gets scheduled only if tran2 DOES NOT complete successfully
        var rollbackTran2 = tran2.ContinueWith(rollback, TaskContinuationOptions.NotOnRanToCompletion);

        // For demo purposes, wait for the sample to complete
        rollbackTran2.Wait();
    }
}

Remarks

The returned Task<TResult> will not be scheduled for execution until the current task has completed. If the criteria specified through the continuationOptions parameter are not met, the continuation task will be canceled instead of scheduled.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

ContinueWith<TResult>(Func<Task,Object,TResult>, Object, CancellationToken)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Creates a continuation that executes asynchronously when the target Task completes and returns a value. The continuation receives caller-supplied state information and a cancellation token.

C#
public System.Threading.Tasks.Task<TResult> ContinueWith<TResult> (Func<System.Threading.Tasks.Task,object,TResult> continuationFunction, object state, System.Threading.CancellationToken cancellationToken);
C#
public System.Threading.Tasks.Task<TResult> ContinueWith<TResult> (Func<System.Threading.Tasks.Task,object?,TResult> continuationFunction, object? state, System.Threading.CancellationToken cancellationToken);

Type Parameters

TResult

The type of the result produced by the continuation.

Parameters

continuationFunction
Func<Task,Object,TResult>

A function to run when the Task completes. When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.

state
Object

An object representing data to be used by the continuation function.

cancellationToken
CancellationToken

The CancellationToken that will be assigned to the new continuation task.

Returns

A new continuation Task<TResult>.

Exceptions

The continuationFunction argument is null.

The provided CancellationToken has already been disposed.

Remarks

The returned Task<TResult> will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

ContinueWith<TResult>(Func<Task,Object,TResult>, Object, TaskContinuationOptions)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Creates a continuation that executes based on the specified task continuation options when the target Task completes. The continuation receives caller-supplied state information.

C#
public System.Threading.Tasks.Task<TResult> ContinueWith<TResult> (Func<System.Threading.Tasks.Task,object,TResult> continuationFunction, object state, System.Threading.Tasks.TaskContinuationOptions continuationOptions);
C#
public System.Threading.Tasks.Task<TResult> ContinueWith<TResult> (Func<System.Threading.Tasks.Task,object?,TResult> continuationFunction, object? state, System.Threading.Tasks.TaskContinuationOptions continuationOptions);

Type Parameters

TResult

The type of the result produced by the continuation.

Parameters

continuationFunction
Func<Task,Object,TResult>

A function to run when the Task completes. When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.

state
Object

An object representing data to be used by the continuation function.

continuationOptions
TaskContinuationOptions

Options for when the continuation is scheduled and how it behaves. This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.

Returns

A new continuation Task<TResult>.

Exceptions

The continuationFunction argument is null.

The continuationOptions argument specifies an invalid value for TaskContinuationOptions.

Remarks

The returned Task<TResult> will not be scheduled for execution until the current task has completed. If the continuation criteria specified through the continuationOptions parameter are not met, the continuation task will be canceled instead of scheduled.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

ContinueWith<TResult>(Func<Task,TResult>, TaskContinuationOptions)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Creates a continuation that executes according to the specified continuation options and returns a value.

C#
public System.Threading.Tasks.Task<TResult> ContinueWith<TResult> (Func<System.Threading.Tasks.Task,TResult> continuationFunction, System.Threading.Tasks.TaskContinuationOptions continuationOptions);

Type Parameters

TResult

The type of the result produced by the continuation.

Parameters

continuationFunction
Func<Task,TResult>

A function to run according to the condition specified in continuationOptions. When run, the delegate will be passed the completed task as an argument.

continuationOptions
TaskContinuationOptions

Options for when the continuation is scheduled and how it behaves. This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.

Returns

A new continuation Task<TResult>.

Exceptions

The Task has been disposed.

The continuationFunction argument is null.

The continuationOptions argument specifies an invalid value for TaskContinuationOptions.

Remarks

The returned Task<TResult> will not be scheduled for execution until the current task has completed. If the continuation criteria specified through the continuationOptions parameter are not met, the continuation task will be canceled instead of scheduled.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

ContinueWith<TResult>(Func<Task,TResult>, TaskScheduler)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Creates a continuation that executes asynchronously when the target Task completes and returns a value. The continuation uses a specified scheduler.

C#
public System.Threading.Tasks.Task<TResult> ContinueWith<TResult> (Func<System.Threading.Tasks.Task,TResult> continuationFunction, System.Threading.Tasks.TaskScheduler scheduler);

Type Parameters

TResult

The type of the result produced by the continuation.

Parameters

continuationFunction
Func<Task,TResult>

A function to run when the Task completes. When run, the delegate will be passed the completed task as an argument.

scheduler
TaskScheduler

The TaskScheduler to associate with the continuation task and to use for its execution.

Returns

A new continuation Task<TResult>.

Exceptions

The Task has been disposed.

The continuationFunction argument is null.

-or-

The scheduler argument is null.

Remarks

The returned Task<TResult> will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

ContinueWith<TResult>(Func<Task,TResult>, CancellationToken)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Creates a continuation that executes asynchronously when the target Task completes and returns a value. The continuation receives a cancellation token.

C#
public System.Threading.Tasks.Task<TResult> ContinueWith<TResult> (Func<System.Threading.Tasks.Task,TResult> continuationFunction, System.Threading.CancellationToken cancellationToken);

Type Parameters

TResult

The type of the result produced by the continuation.

Parameters

continuationFunction
Func<Task,TResult>

A function to run when the Task completes. When run, the delegate will be passed the completed task as an argument.

cancellationToken
CancellationToken

The CancellationToken that will be assigned to the new continuation task.

Returns

A new continuation Task<TResult>.

Exceptions

The Task has been disposed.

-or-

The CancellationTokenSource that created the token has already been disposed.

The continuationFunction argument is null.

Remarks

The returned Task<TResult> will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

ContinueWith<TResult>(Func<Task,Object,TResult>, Object)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Creates a continuation that receives caller-supplied state information and executes asynchronously when the target Task completes and returns a value.

C#
public System.Threading.Tasks.Task<TResult> ContinueWith<TResult> (Func<System.Threading.Tasks.Task,object,TResult> continuationFunction, object state);
C#
public System.Threading.Tasks.Task<TResult> ContinueWith<TResult> (Func<System.Threading.Tasks.Task,object?,TResult> continuationFunction, object? state);

Type Parameters

TResult

The type of the result produced by the continuation.

Parameters

continuationFunction
Func<Task,Object,TResult>

A function to run when the Task completes. When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.

state
Object

An object representing data to be used by the continuation function.

Returns

A new continuation Task<TResult>.

Exceptions

The continuationFunction argument is null.

Remarks

The returned Task<TResult> will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

ContinueWith<TResult>(Func<Task,TResult>)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Creates a continuation that executes asynchronously when the target Task<TResult> completes and returns a value.

C#
public System.Threading.Tasks.Task<TResult> ContinueWith<TResult> (Func<System.Threading.Tasks.Task,TResult> continuationFunction);

Type Parameters

TResult

The type of the result produced by the continuation.

Parameters

continuationFunction
Func<Task,TResult>

A function to run when the Task<TResult> completes. When run, the delegate will be passed the completed task as an argument.

Returns

A new continuation task.

Exceptions

The Task has been disposed.

The continuationFunction argument is null.

Examples

The following example shows how to use the ContinueWith method:

C#
using System;
using System.Threading;
using System.Threading.Tasks;

class ContinuationSimpleDemo
{
    // Demonstrated features:
    // 		Task.Factory
    //		Task.ContinueWith()
    //		Task.Wait()
    // Expected results:
    // 		A sequence of three unrelated tasks is created and executed in this order - alpha, beta, gamma.
    //		A sequence of three related tasks is created - each task negates its argument and passes is to the next task: 5, -5, 5 is printed.
    //		A sequence of three unrelated tasks is created where tasks have different types.
    // Documentation:
    //		http://msdn.microsoft.com/library/system.threading.tasks.taskfactory_members(VS.100).aspx
    static void Main()
    {
        Action<string> action =
            (str) =>
                Console.WriteLine("Task={0}, str={1}, Thread={2}", Task.CurrentId, str, Thread.CurrentThread.ManagedThreadId);

        // Creating a sequence of action tasks (that return no result).
        Console.WriteLine("Creating a sequence of action tasks (that return no result)");
        Task.Factory.StartNew(() => action("alpha"))
            .ContinueWith(antecendent => action("beta"))        // Antecedent data is ignored
            .ContinueWith(antecendent => action("gamma"))
            .Wait();

        Func<int, int> negate =
            (n) =>
            {
                Console.WriteLine("Task={0}, n={1}, -n={2}, Thread={3}", Task.CurrentId, n, -n, Thread.CurrentThread.ManagedThreadId);
                return -n;
            };

        // Creating a sequence of function tasks where each continuation uses the result from its antecendent
        Console.WriteLine("\nCreating a sequence of function tasks where each continuation uses the result from its antecendent");
        Task<int>.Factory.StartNew(() => negate(5))
            .ContinueWith(antecendent => negate(antecendent.Result))		// Antecedent result feeds into continuation
            .ContinueWith(antecendent => negate(antecendent.Result))
            .Wait();

        // Creating a sequence of tasks where you can mix and match the types
        Console.WriteLine("\nCreating a sequence of tasks where you can mix and match the types");
        Task<int>.Factory.StartNew(() => negate(6))
            .ContinueWith(antecendent => action("x"))
            .ContinueWith(antecendent => negate(7))
            .Wait();
    }
}

Remarks

The returned Task<TResult> will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting out early due to being canceled.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0