Task<TResult>.ContinueWith Método
Definição
Cria uma tarefa de continuação executada quando outra tarefa é concluída.Creates a continuation task that executes when another task completes.
Sobrecargas
ContinueWith(Action<Task<TResult>,Object>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler) |
Criará uma continuação executada quando o Task<TResult> de destino for concluído.Creates a continuation that executes when the target Task<TResult> completes. |
ContinueWith(Action<Task<TResult>>, CancellationToken, TaskContinuationOptions, TaskScheduler) |
Cria uma continuação executada de acordo com a condição especificada em |
ContinueWith(Action<Task<TResult>,Object>, Object, TaskScheduler) |
Criará uma continuação executada quando o Task<TResult> de destino for concluído.Creates a continuation that executes when the target Task<TResult> completes. |
ContinueWith(Action<Task<TResult>,Object>, Object, CancellationToken) |
Criará uma continuação executada quando o Task<TResult> de destino for concluído.Creates a continuation that executes when the target Task<TResult> completes. |
ContinueWith(Action<Task<TResult>,Object>, Object, TaskContinuationOptions) |
Criará uma continuação executada quando o Task<TResult> de destino for concluído.Creates a continuation that executes when the target Task<TResult> completes. |
ContinueWith(Action<Task<TResult>>, TaskContinuationOptions) |
Cria uma continuação executada de acordo com a condição especificada em |
ContinueWith(Action<Task<TResult>>, CancellationToken) |
Cria uma continuação cancelável executada de forma assíncrona quando a Task<TResult> de destino for concluída.Creates a cancelable continuation that executes asynchronously when the target Task<TResult> completes. |
ContinueWith(Action<Task<TResult>,Object>, Object) |
Cria uma continuação que recebe informações de estado e executa quando a Task<TResult> de destino for concluída.Creates a continuation that is passed state information and that executes when the target Task<TResult> completes. |
ContinueWith(Action<Task<TResult>>) |
Cria uma continuação que é executada de forma assíncrona quando a tarefa de destino é concluída.Creates a continuation that executes asynchronously when the target task completes. |
ContinueWith(Action<Task<TResult>>, TaskScheduler) |
Criará uma continuação executada de forma assíncrona quando o Task<TResult> de destino for concluído.Creates a continuation that executes asynchronously when the target Task<TResult> completes. |
ContinueWith<TNewResult>(Func<Task<TResult>,Object,TNewResult>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler) |
Criará uma continuação executada quando o Task<TResult> de destino for concluído.Creates a continuation that executes when the target Task<TResult> completes. |
ContinueWith<TNewResult>(Func<Task<TResult>,TNewResult>, CancellationToken, TaskContinuationOptions, TaskScheduler) |
Cria uma continuação executada de acordo com a condição especificada em |
ContinueWith<TNewResult>(Func<Task<TResult>,Object,TNewResult>, Object, TaskScheduler) |
Criará uma continuação executada quando o Task<TResult> de destino for concluído.Creates a continuation that executes when the target Task<TResult> completes. |
ContinueWith<TNewResult>(Func<Task<TResult>,Object,TNewResult>, Object, TaskContinuationOptions) |
Criará uma continuação executada quando o Task<TResult> de destino for concluído.Creates a continuation that executes when the target Task<TResult> completes. |
ContinueWith<TNewResult>(Func<Task<TResult>,Object,TNewResult>, Object, CancellationToken) |
Criará uma continuação executada quando o Task<TResult> de destino for concluído.Creates a continuation that executes when the target Task<TResult> completes. |
ContinueWith<TNewResult>(Func<Task<TResult>,TNewResult>, TaskContinuationOptions) |
Cria uma continuação executada de acordo com a condição especificada em |
ContinueWith<TNewResult>(Func<Task<TResult>,TNewResult>, CancellationToken) |
Criará uma continuação executada de forma assíncrona quando o Task<TResult> de destino for concluído.Creates a continuation that executes asynchronously when the target Task<TResult> completes. |
ContinueWith<TNewResult>(Func<Task<TResult>,Object,TNewResult>, Object) |
Criará uma continuação executada quando o Task<TResult> de destino for concluído.Creates a continuation that executes when the target Task<TResult> completes. |
ContinueWith<TNewResult>(Func<Task<TResult>,TNewResult>) |
Criará uma continuação executada de forma assíncrona quando o Task<TResult> de destino for concluído.Creates a continuation that executes asynchronously when the target Task<TResult> completes. |
ContinueWith<TNewResult>(Func<Task<TResult>,TNewResult>, TaskScheduler) |
Criará uma continuação executada de forma assíncrona quando o Task<TResult> de destino for concluído.Creates a continuation that executes asynchronously when the target Task<TResult> completes. |
ContinueWith(Action<Task<TResult>,Object>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler)
Criará uma continuação executada quando o Task<TResult> de destino for concluído.Creates a continuation that executes when the target Task<TResult> completes.
public:
System::Threading::Tasks::Task ^ ContinueWith(Action<System::Threading::Tasks::Task<TResult> ^, System::Object ^> ^ continuationAction, System::Object ^ state, System::Threading::CancellationToken cancellationToken, System::Threading::Tasks::TaskContinuationOptions continuationOptions, System::Threading::Tasks::TaskScheduler ^ scheduler);
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task<TResult>,object> continuationAction, object state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskContinuationOptions continuationOptions, System.Threading.Tasks.TaskScheduler scheduler);
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task<TResult>,object?> continuationAction, object? state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskContinuationOptions continuationOptions, System.Threading.Tasks.TaskScheduler scheduler);
override this.ContinueWith : Action<System.Threading.Tasks.Task<'Result>, obj> * obj * System.Threading.CancellationToken * System.Threading.Tasks.TaskContinuationOptions * System.Threading.Tasks.TaskScheduler -> System.Threading.Tasks.Task
Public Function ContinueWith (continuationAction As Action(Of Task(Of TResult), Object), state As Object, cancellationToken As CancellationToken, continuationOptions As TaskContinuationOptions, scheduler As TaskScheduler) As Task
Parâmetros
Uma ação a ser executada quando o Task<TResult> for concluído.An action to run when the Task<TResult> completes. Quando a ação for executada, a tarefa concluída e o objeto de estado fornecido pelo chamador serão passados como argumentos ao delegado.When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.
- state
- Object
Um objeto que representa os dados a serem usados pela ação de continuação.An object representing data to be used by the continuation action.
- cancellationToken
- CancellationToken
O CancellationToken que será atribuído à nova tarefa de continuação.The CancellationToken that will be assigned to the new continuation task.
- continuationOptions
- TaskContinuationOptions
Opções para quando a continuação é agendada e como ela se comporta.Options for when the continuation is scheduled and how it behaves. Isso inclui critérios como OnlyOnCanceled, além de opções de execução como ExecuteSynchronously.This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.
- scheduler
- TaskScheduler
O TaskScheduler a ser associado à tarefa de continuação e a ser usado para sua execução.The TaskScheduler to associate with the continuation task and to use for its execution.
Retornos
Um novo Task de continuação.A new continuation Task.
Exceções
O argumento scheduler
é null
.The scheduler
argument is null
.
O argumento continuationOptions
especifica um valor inválido para TaskContinuationOptions.The continuationOptions
argument specifies an invalid value for TaskContinuationOptions.
O CancellationToken fornecido já foi descartado.The provided CancellationToken has already been disposed.
Comentários
O retornado Task não será agendado para execução até que a tarefa atual seja concluída.The returned Task will not be scheduled for execution until the current task has completed. Se os critérios especificados por meio do continuationOptions
parâmetro não forem atendidos, a tarefa de continuação será cancelada, em vez de agendada.If the criteria specified through the continuationOptions
parameter are not met, the continuation task will be canceled instead of scheduled.
Confira também
Aplica-se a
ContinueWith(Action<Task<TResult>>, CancellationToken, TaskContinuationOptions, TaskScheduler)
Cria uma continuação executada de acordo com a condição especificada em continuationOptions
.Creates a continuation that executes according the condition specified in continuationOptions
.
public:
System::Threading::Tasks::Task ^ ContinueWith(Action<System::Threading::Tasks::Task<TResult> ^> ^ continuationAction, System::Threading::CancellationToken cancellationToken, System::Threading::Tasks::TaskContinuationOptions continuationOptions, System::Threading::Tasks::TaskScheduler ^ scheduler);
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task<TResult>> continuationAction, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskContinuationOptions continuationOptions, System.Threading.Tasks.TaskScheduler scheduler);
override this.ContinueWith : Action<System.Threading.Tasks.Task<'Result>> * System.Threading.CancellationToken * System.Threading.Tasks.TaskContinuationOptions * System.Threading.Tasks.TaskScheduler -> System.Threading.Tasks.Task
Public Function ContinueWith (continuationAction As Action(Of Task(Of TResult)), cancellationToken As CancellationToken, continuationOptions As TaskContinuationOptions, scheduler As TaskScheduler) As Task
Parâmetros
Uma ação a ser executada de acordo com a condição especificada em continuationOptions
.An action to run according the condition specified in continuationOptions
. Quando executado, o delegado passará a tarefa concluída como um argumento.When run, the delegate will be passed the completed task as an argument.
- cancellationToken
- CancellationToken
O CancellationToken que será atribuído à nova tarefa de continuação.The CancellationToken that will be assigned to the new continuation task.
- continuationOptions
- TaskContinuationOptions
Opções para quando a continuação é agendada e como ela se comporta.Options for when the continuation is scheduled and how it behaves. Isso inclui critérios como OnlyOnCanceled, além de opções de execução como ExecuteSynchronously.This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.
- scheduler
- TaskScheduler
O TaskScheduler a ser associado à tarefa de continuação e a ser usado para sua execução.The TaskScheduler to associate with the continuation task and to use for its execution.
Retornos
Um novo Task de continuação.A new continuation Task.
Exceções
O Task<TResult> foi descartado.The Task<TResult> has been disposed.
- ou --or-
O CancellationTokenSource que criou cancellationToken
já foi descartado.The CancellationTokenSource that created cancellationToken
has already been disposed.
O argumento continuationAction
é null
.The continuationAction
argument is null
.
- ou --or-
O argumento scheduler
é null
.The scheduler
argument is null
.
O argumento continuationOptions
especifica um valor inválido para TaskContinuationOptions.The continuationOptions
argument specifies an invalid value for TaskContinuationOptions.
Comentários
O retornado Task não será agendado para execução até que a tarefa atual seja concluída.The returned Task will not be scheduled for execution until the current task has completed. Se os critérios especificados por meio do continuationOptions
parâmetro não forem atendidos, a tarefa de continuação será cancelada, em vez de agendada.If the criteria specified through the continuationOptions
parameter are not met, the continuation task will be canceled instead of scheduled. Para obter mais informações, consulte Encadeando tarefas com tarefas de continuação.For more information, see Chaining Tasks by Using Continuation Tasks.
Confira também
- Biblioteca de tarefas paralelas (TPL)Task Parallel Library (TPL)
- Programação assíncrona baseada em tarefasTask-based Asynchronous Programming
- Encadeando tarefas com tarefas de continuaçãoChaining Tasks by Using Continuation Tasks
Aplica-se a
ContinueWith(Action<Task<TResult>,Object>, Object, TaskScheduler)
Criará uma continuação executada quando o Task<TResult> de destino for concluído.Creates a continuation that executes when the target Task<TResult> completes.
public:
System::Threading::Tasks::Task ^ ContinueWith(Action<System::Threading::Tasks::Task<TResult> ^, System::Object ^> ^ continuationAction, System::Object ^ state, System::Threading::Tasks::TaskScheduler ^ scheduler);
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task<TResult>,object> continuationAction, object state, System.Threading.Tasks.TaskScheduler scheduler);
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task<TResult>,object?> continuationAction, object? state, System.Threading.Tasks.TaskScheduler scheduler);
override this.ContinueWith : Action<System.Threading.Tasks.Task<'Result>, obj> * obj * System.Threading.Tasks.TaskScheduler -> System.Threading.Tasks.Task
Public Function ContinueWith (continuationAction As Action(Of Task(Of TResult), Object), state As Object, scheduler As TaskScheduler) As Task
Parâmetros
Uma ação a ser executada quando o Task<TResult> for concluído.An action to run when the Task<TResult> completes. Quando executada, a tarefa concluída e o objeto de estado fornecido pelo chamador serão passados como argumentos ao delegado.When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.
- state
- Object
Um objeto que representa os dados a serem usados pela ação de continuação.An object representing data to be used by the continuation action.
- scheduler
- TaskScheduler
O TaskScheduler a ser associado à tarefa de continuação e a ser usado para sua execução.The TaskScheduler to associate with the continuation task and to use for its execution.
Retornos
Um novo Task de continuação.A new continuation Task.
Exceções
O argumento scheduler
é null
.The scheduler
argument is null
.
Comentários
O retornado Task não será agendado para execução até que a tarefa atual seja concluída, seja ela concluída devido à conclusão com êxito, com falha devido a uma exceção sem tratamento ou que seja encerrada antecipadamente devido a ser cancelada.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.
Confira também
Aplica-se a
ContinueWith(Action<Task<TResult>,Object>, Object, CancellationToken)
Criará uma continuação executada quando o Task<TResult> de destino for concluído.Creates a continuation that executes when the target Task<TResult> completes.
public:
System::Threading::Tasks::Task ^ ContinueWith(Action<System::Threading::Tasks::Task<TResult> ^, System::Object ^> ^ continuationAction, System::Object ^ state, System::Threading::CancellationToken cancellationToken);
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task<TResult>,object> continuationAction, object state, System.Threading.CancellationToken cancellationToken);
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task<TResult>,object?> continuationAction, object? state, System.Threading.CancellationToken cancellationToken);
override this.ContinueWith : Action<System.Threading.Tasks.Task<'Result>, obj> * obj * System.Threading.CancellationToken -> System.Threading.Tasks.Task
Public Function ContinueWith (continuationAction As Action(Of Task(Of TResult), Object), state As Object, cancellationToken As CancellationToken) As Task
Parâmetros
Uma ação a ser executada quando o Task<TResult> for concluído.An action to run when the Task<TResult> completes. Quando a ação for executada, a tarefa concluída e o objeto de estado fornecido pelo chamador serão passados como argumentos ao delegado.When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.
- state
- Object
Um objeto que representa os dados a serem usados pela ação de continuação.An object representing data to be used by the continuation action.
- cancellationToken
- CancellationToken
O CancellationToken que será atribuído à nova tarefa de continuação.The CancellationToken that will be assigned to the new continuation task.
Retornos
Um novo Task de continuação.A new continuation Task.
Exceções
O argumento continuationAction
é null
.The continuationAction
argument is null
.
O CancellationToken fornecido já foi descartado.The provided CancellationToken has already been disposed.
Comentários
O retornado Task não será agendado para execução até que a tarefa atual seja concluída, seja ela concluída devido à conclusão com êxito, com falha devido a uma exceção sem tratamento ou que seja encerrada antecipadamente devido a ser cancelada.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.
Confira também
Aplica-se a
ContinueWith(Action<Task<TResult>,Object>, Object, TaskContinuationOptions)
Criará uma continuação executada quando o Task<TResult> de destino for concluído.Creates a continuation that executes when the target Task<TResult> completes.
public:
System::Threading::Tasks::Task ^ ContinueWith(Action<System::Threading::Tasks::Task<TResult> ^, System::Object ^> ^ continuationAction, System::Object ^ state, System::Threading::Tasks::TaskContinuationOptions continuationOptions);
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task<TResult>,object> continuationAction, object state, System.Threading.Tasks.TaskContinuationOptions continuationOptions);
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task<TResult>,object?> continuationAction, object? state, System.Threading.Tasks.TaskContinuationOptions continuationOptions);
override this.ContinueWith : Action<System.Threading.Tasks.Task<'Result>, obj> * obj * System.Threading.Tasks.TaskContinuationOptions -> System.Threading.Tasks.Task
Public Function ContinueWith (continuationAction As Action(Of Task(Of TResult), Object), state As Object, continuationOptions As TaskContinuationOptions) As Task
Parâmetros
Uma ação a ser executada quando o Task<TResult> for concluído.An action to run when the Task<TResult> completes. Quando a ação for executada, a tarefa concluída e o objeto de estado fornecido pelo chamador serão passados como argumentos ao delegado.When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.
- state
- Object
Um objeto que representa os dados a serem usados pela ação de continuação.An object representing data to be used by the continuation action.
- continuationOptions
- TaskContinuationOptions
Opções para quando a continuação é agendada e como ela se comporta.Options for when the continuation is scheduled and how it behaves. Isso inclui critérios como OnlyOnCanceled, além de opções de execução como ExecuteSynchronously.This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.
Retornos
Um novo Task de continuação.A new continuation Task.
Exceções
O argumento continuationAction
é null
.The continuationAction
argument is null
.
O argumento continuationOptions
especifica um valor inválido para TaskContinuationOptions.The continuationOptions
argument specifies an invalid value for TaskContinuationOptions.
Comentários
O retornado Task não será agendado para execução até que a tarefa atual seja concluída.The returned Task will not be scheduled for execution until the current task has completed. Se os critérios de continuação especificados por meio do continuationOptions
parâmetro não forem atendidos, a tarefa de continuação será cancelada em vez de agendada.If the continuation criteria specified through the continuationOptions
parameter are not met, the continuation task will be canceled instead of scheduled.
Confira também
Aplica-se a
ContinueWith(Action<Task<TResult>>, TaskContinuationOptions)
Cria uma continuação executada de acordo com a condição especificada em continuationOptions
.Creates a continuation that executes according the condition specified in continuationOptions
.
public:
System::Threading::Tasks::Task ^ ContinueWith(Action<System::Threading::Tasks::Task<TResult> ^> ^ continuationAction, System::Threading::Tasks::TaskContinuationOptions continuationOptions);
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task<TResult>> continuationAction, System.Threading.Tasks.TaskContinuationOptions continuationOptions);
override this.ContinueWith : Action<System.Threading.Tasks.Task<'Result>> * System.Threading.Tasks.TaskContinuationOptions -> System.Threading.Tasks.Task
Public Function ContinueWith (continuationAction As Action(Of Task(Of TResult)), continuationOptions As TaskContinuationOptions) As Task
Parâmetros
Uma ação de acordo com a condição especificada em continuationOptions
.An action to according the condition specified in continuationOptions
. Quando executado, o delegado passará a tarefa concluída como um argumento.When run, the delegate will be passed the completed task as an argument.
- continuationOptions
- TaskContinuationOptions
Opções para quando a continuação é agendada e como ela se comporta.Options for when the continuation is scheduled and how it behaves. Isso inclui critérios como OnlyOnCanceled, além de opções de execução como ExecuteSynchronously.This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.
Retornos
Um novo Task de continuação.A new continuation Task.
Exceções
O Task<TResult> foi descartado.The Task<TResult> has been disposed.
O argumento continuationAction
é null
.The continuationAction
argument is null
.
O argumento continuationOptions
especifica um valor inválido para TaskContinuationOptions.The continuationOptions
argument specifies an invalid value for TaskContinuationOptions.
Comentários
O retornado Task não será agendado para execução até que a tarefa atual seja concluída.The returned Task will not be scheduled for execution until the current task has completed. Se os critérios de continuação especificados por meio do continuationOptions
parâmetro não forem atendidos, a tarefa de continuação será cancelada em vez de agendada.If the continuation criteria specified through the continuationOptions
parameter are not met, the continuation task will be canceled instead of scheduled.
Para obter mais informações, consulte Encadeando tarefas com tarefas de continuação.For more information, see Chaining Tasks by Using Continuation Tasks.
Confira também
- Biblioteca de tarefas paralelas (TPL)Task Parallel Library (TPL)
- Programação assíncrona baseada em tarefasTask-based Asynchronous Programming
- Encadeando tarefas com tarefas de continuaçãoChaining Tasks by Using Continuation Tasks
Aplica-se a
ContinueWith(Action<Task<TResult>>, CancellationToken)
Cria uma continuação cancelável executada de forma assíncrona quando a Task<TResult> de destino for concluída.Creates a cancelable continuation that executes asynchronously when the target Task<TResult> completes.
public:
System::Threading::Tasks::Task ^ ContinueWith(Action<System::Threading::Tasks::Task<TResult> ^> ^ continuationAction, System::Threading::CancellationToken cancellationToken);
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task<TResult>> continuationAction, System.Threading.CancellationToken cancellationToken);
override this.ContinueWith : Action<System.Threading.Tasks.Task<'Result>> * System.Threading.CancellationToken -> System.Threading.Tasks.Task
Public Function ContinueWith (continuationAction As Action(Of Task(Of TResult)), cancellationToken As CancellationToken) As Task
Parâmetros
Uma ação a ser executada quando o Task<TResult> for concluído.An action to run when the Task<TResult> completes. Quando executado, o delegado recebe a tarefa concluída como um argumento.When run, the delegate is passed the completed task as an argument.
- cancellationToken
- CancellationToken
O token de cancelamento transmitido à nova tarefa de continuação.The cancellation token that is passed to the new continuation task.
Retornos
Uma nova tarefa de continuação.A new continuation task.
Exceções
O Task<TResult> foi descartado.The Task<TResult> has been disposed.
- ou --or-
O CancellationTokenSource que criou cancellationToken
foi descartado.The CancellationTokenSource that created cancellationToken
has been disposed.
O argumento continuationAction
é null
.The continuationAction
argument is null
.
Exemplos
O exemplo a seguir cria uma tarefa Antecedent que usa Sieve de Eratosthenes para calcular os números primos entre 1 e um valor inserido pelo usuário.The following example creates an antecedent task that uses the Sieve of Eratosthenes to calculate the prime numbers between 1 and a value entered by the user. Uma matriz é usada para manter informações sobre os números primos.An array is used to hold information about the prime numbers. O índice de matriz representa o número e o valor do elemento indica se esse número é composto (seu valor é true
) ou primo (seu valor é false
).The array index represents the number, and the element's value indicates whether that number is composite (its value is true
) or prime (its value is false
). Essa tarefa é passada para uma tarefa de continuação, que é responsável por extrair os números primos da matriz de inteiros e exibi-los.This task is then passed to a continuation task, which is responsible for extracting the prime numbers from the integer array and displaying them.
Um token de cancelamento é passado para o Antecedent e para a tarefa de continuação.A cancellation token is passed to both the antecedent and the continuation task. Um System.Timers.Timer objeto é usado para definir um valor de tempo limite de 100 milissegundos.A System.Timers.Timer object is used to define a timeout value of 100 milliseconds. Se o evento for acionado, o CancellationTokenSource.Cancel método será chamado e o token de cancelamento será usado para solicitar o cancelamento das tarefas.If the event fires, the CancellationTokenSource.Cancel method is called, and the cancellation token is used to request cancellation of the tasks.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Timers = System.Timers;
public class Example
{
static CancellationTokenSource ts;
public static void Main(string[] args)
{
int upperBound = args.Length >= 1 ? Int32.Parse(args[0]) : 200;
ts = new CancellationTokenSource();
CancellationToken token = ts.Token;
Timers.Timer timer = new Timers.Timer(3000);
timer.Elapsed += TimedOutEvent;
timer.AutoReset = false;
timer.Enabled = true;
var t1 = Task.Run(() => { // True = composite.
// False = prime.
bool[] values = new bool[upperBound + 1];
for (int ctr = 2; ctr <= (int) Math.Sqrt(upperBound); ctr++) {
if (values[ctr] == false) {
for (int product = ctr * ctr; product <= upperBound;
product = product + ctr)
values[product] = true;
}
token.ThrowIfCancellationRequested();
}
return values; }, token);
var t2 = t1.ContinueWith( (antecedent) => { // Create a list of prime numbers.
var primes = new List<int>();
token.ThrowIfCancellationRequested();
bool[] numbers = antecedent.Result;
string output = String.Empty;
for (int ctr = 1; ctr <= numbers.GetUpperBound(0); ctr++)
if (numbers[ctr] == false)
primes.Add(ctr);
// Create the output string.
for (int ctr = 0; ctr < primes.Count; ctr++) {
token.ThrowIfCancellationRequested();
output += primes[ctr].ToString("N0");
if (ctr < primes.Count - 1)
output += ", ";
if ((ctr + 1) % 8 == 0)
output += Environment.NewLine;
}
//Display the result.
Console.WriteLine("Prime numbers from 1 to {0}:\n",
upperBound);
Console.WriteLine(output);
}, token);
try {
t2.Wait();
}
catch (AggregateException ae) {
foreach (var e in ae.InnerExceptions) {
if (e.GetType() == typeof(TaskCanceledException))
Console.WriteLine("The operation was cancelled.");
else
Console.WriteLine("ELSE: {0}: {1}", e.GetType().Name, e.Message);
}
}
finally {
ts.Dispose();
}
}
private static void TimedOutEvent(Object source, Timers.ElapsedEventArgs e)
{
ts.Cancel();
}
}
// If cancellation is not requested, the example displays output like the following:
// Prime numbers from 1 to 400:
//
// 1, 2, 3, 5, 7, 11, 13, 17,
// 19, 23, 29, 31, 37, 41, 43, 47,
// 53, 59, 61, 67, 71, 73, 79, 83,
// 89, 97, 101, 103, 107, 109, 113, 127,
// 131, 137, 139, 149, 151, 157, 163, 167,
// 173, 179, 181, 191, 193, 197, 199, 211,
// 223, 227, 229, 233, 239, 241, 251, 257,
// 263, 269, 271, 277, 281, 283, 293, 307,
// 311, 313, 317, 331, 337, 347, 349, 353,
// 359, 367, 373, 379, 383, 389, 397, 401
// If cancellation is requested, the example displays output like the following:
// The operation was cancelled.
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks
Imports Timers = System.Timers
Module Example
Dim ts As CancellationTokenSource
Public Sub Main(args() As String)
Dim upperBound As Integer = If(args.Length >= 1, CInt(args(0)), 200)
ts = New CancellationTokenSource()
Dim token As CancellationToken = ts.Token
Dim timer As New Timers.Timer(100)
AddHandler timer.Elapsed, AddressOf TimedOutEvent
timer.AutoReset = False
timer.Enabled = True
Dim t1 = Task.Run(Function()
' True = composite.
' False = prime.
Dim values(upperBound) As Boolean
For ctr = 2 To CInt(Math.Sqrt(upperBound))
If values(ctr) = False Then
For product = ctr * ctr To upperBound Step ctr
values(product) = True
Next
End If
token.ThrowIfCancellationRequested()
Next
Return values
End Function, token)
Dim t2 = t1.ContinueWith(Sub(antecedent)
' Create a list of prime numbers.
Dim primes As New List(Of Integer)()
token.ThrowIfCancellationRequested()
Dim numbers As Boolean() = antecedent.Result
Dim output As String = String.Empty
For ctr As Integer = 1 To numbers.GetUpperBound(0)
If numbers(ctr) = False Then primes.Add(ctr)
Next
' Create the output string.
For ctr As Integer = 0 To primes.Count - 1
token.ThrowIfCancellationRequested()
output += primes(ctr).ToString("N0")
If ctr < primes.Count - 1 Then output += ", "
If (ctr + 1) Mod 8 = 0 Then output += vbCrLf
Next
'Display the result.
Console.WriteLine("Prime numbers from 1 to {0}:{1}",
upperBound, vbCrLf)
Console.WriteLine(output)
End Sub, token)
Try
t2.Wait()
Catch ae As AggregateException
For Each e In ae.InnerExceptions
If e.GetType Is GetType(TaskCanceledException) Then
Console.WriteLine("The operation was cancelled.")
Else
Console.WriteLine("{0}: {1}", e.GetType().Name, e.Message)
End If
Next
Finally
ts.Dispose()
End Try
End Sub
Private Sub TimedOutEvent(source As Object, e As Timers.ElapsedEventArgs)
ts.Cancel()
End Sub
End Module
' If cancellation is not requested, the example displays output like the following:
' Prime numbers from 1 to 400:
'
' 1, 2, 3, 5, 7, 11, 13, 17,
' 19, 23, 29, 31, 37, 41, 43, 47,
' 53, 59, 61, 67, 71, 73, 79, 83,
' 89, 97, 101, 103, 107, 109, 113, 127,
' 131, 137, 139, 149, 151, 157, 163, 167,
' 173, 179, 181, 191, 193, 197, 199, 211,
' 223, 227, 229, 233, 239, 241, 251, 257,
' 263, 269, 271, 277, 281, 283, 293, 307,
' 311, 313, 317, 331, 337, 347, 349, 353,
' 359, 367, 373, 379, 383, 389, 397, 401
' If cancellation is requested, the example displays output like the following:
' The operation was cancelled.
Normalmente, o fornecimento de um valor de aproximadamente 100.000 faz com que o intervalo de tempo limite expire e o Timer.Elapsed evento seja acionado, e a solicitação de cancelamento seja definida.Typically, supplying a value of about 100,000 causes the timeout interval to expire and the Timer.Elapsed event to fire, and the cancellation request to be set.
Comentários
O retornado Task não será agendado para execução até que a tarefa atual seja concluída, seja ela concluída devido à conclusão com êxito, com falha devido a uma exceção sem tratamento ou que seja encerrada antecipadamente devido a ser cancelada.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.
Confira também
- Biblioteca de tarefas paralelas (TPL)Task Parallel Library (TPL)
- Programação assíncrona baseada em tarefasTask-based Asynchronous Programming
- Encadeando tarefas com tarefas de continuaçãoChaining Tasks by Using Continuation Tasks
Aplica-se a
ContinueWith(Action<Task<TResult>,Object>, Object)
Cria uma continuação que recebe informações de estado e executa quando a Task<TResult> de destino for concluída.Creates a continuation that is passed state information and that executes when the target Task<TResult> completes.
public:
System::Threading::Tasks::Task ^ ContinueWith(Action<System::Threading::Tasks::Task<TResult> ^, System::Object ^> ^ continuationAction, System::Object ^ state);
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task<TResult>,object> continuationAction, object state);
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task<TResult>,object?> continuationAction, object? state);
override this.ContinueWith : Action<System.Threading.Tasks.Task<'Result>, obj> * obj -> System.Threading.Tasks.Task
Public Function ContinueWith (continuationAction As Action(Of Task(Of TResult), Object), state As Object) As Task
Parâmetros
Uma ação a ser executada quando o Task<TResult> for concluído.An action to run when the Task<TResult> completes. Quando executado, o delegado recebe a tarefa concluída e um objeto de estado fornecido pelo chamador como argumentos.When run, the delegate is passed the completed task and the caller-supplied state object as arguments.
- state
- Object
Um objeto que representa os dados a serem usados pela ação de continuação.An object representing data to be used by the continuation action.
Retornos
Um novo Task de continuação.A new continuation Task.
Exceções
O argumento continuationAction
é null
.The continuationAction
argument is null
.
Exemplos
O exemplo a seguir cria uma tarefa que é passada como um inteiro entre 2 e 20 e retorna uma matriz que contém os dez primeiros expoentes (de n1 a n10) desse número.The following example creates a task that is passed an integer between 2 and 20 and returns an array that contains the first ten exponents (from n1 to n10) of that number. Em seguida, uma tarefa de continuação é responsável por exibir os expoentes.A continuation task is then responsible for displaying the exponents. Ele é passado tanto ao Antecedent quanto ao número original cujos expoentes o antecedente gera.It is passed both the antecedent and the original number whose exponents the antecedent generates.
using System;
using System.Threading;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
var cts = new CancellationTokenSource();
var token = cts.Token;
// Get an integer to generate a list of its exponents.
var rnd = new Random();
var number = rnd.Next(2, 21);
var t = Task.Factory.StartNew( (value) => { int n = (int) value;
long[] values = new long[10];
for (int ctr = 1; ctr <= 10; ctr++)
values[ctr - 1] = (long) Math.Pow(n, ctr);
return values;
}, number);
var continuation = t.ContinueWith( (antecedent, value) => { Console.WriteLine("Exponents of {0}:", value);
for (int ctr = 0; ctr <= 9; ctr++)
Console.WriteLine(" {0} {1} {2} = {3:N0}",
value, "\u02C6", ctr + 1,
antecedent.Result[ctr]);
Console.WriteLine();
}, number);
continuation.Wait();
cts.Dispose();
}
}
// The example displays output like the following:
// Exponents of 2:
// 2 ^ 1 = 2
// 2 ^ 2 = 4
// 2 ^ 3 = 8
// 2 ^ 4 = 16
// 2 ^ 5 = 32
// 2 ^ 6 = 64
// 2 ^ 7 = 128
// 2 ^ 8 = 256
// 2 ^ 9 = 512
// 2 ^ 10 = 1,024
Imports System.Threading
Imports System.Threading.Tasks
Module Example
Public Sub Main()
Dim cts As New CancellationTokenSource()
Dim token As CancellationToken = cts.Token
' Get an integer to generate a list of its exponents.
Dim rnd As New Random()
Dim number As Integer = rnd.Next(2, 21)
Dim t = Task.Factory.StartNew( Function(value)
Dim n As Integer = CInt(value)
Dim values(9) As Long
For ctr As Integer = 1 To 10
values(ctr - 1) = CLng(Math.Pow(n, ctr))
Next
return values
End Function, number)
Dim continuation = t.ContinueWith( Sub(antecedent, value)
Console.WriteLine("Exponents of {0}:", value)
For ctr As Integer = 0 To 9
Console.WriteLine(" {0} {1} {2} = {3:N0}",
value, ChrW(&h02C6), ctr + 1,
antecedent.Result(ctr))
Next
Console.WriteLine()
End Sub, number)
continuation.Wait()
cts.Dispose()
End Sub
End Module
' The example displays output like the following:
' Exponents of 2:
' 2 ^ 1 = 2
' 2 ^ 2 = 4
' 2 ^ 3 = 8
' 2 ^ 4 = 16
' 2 ^ 5 = 32
' 2 ^ 6 = 64
' 2 ^ 7 = 128
' 2 ^ 8 = 256
' 2 ^ 9 = 512
' 2 ^ 10 = 1,024
Comentários
O retornado Task não será agendado para execução até que a tarefa atual seja concluída, seja ela concluída devido à conclusão com êxito, com falha devido a uma exceção sem tratamento ou que seja encerrada antecipadamente devido a ser cancelada.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.
Confira também
Aplica-se a
ContinueWith(Action<Task<TResult>>)
Cria uma continuação que é executada de forma assíncrona quando a tarefa de destino é concluída.Creates a continuation that executes asynchronously when the target task completes.
public:
System::Threading::Tasks::Task ^ ContinueWith(Action<System::Threading::Tasks::Task<TResult> ^> ^ continuationAction);
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task<TResult>> continuationAction);
override this.ContinueWith : Action<System.Threading.Tasks.Task<'Result>> -> System.Threading.Tasks.Task
Public Function ContinueWith (continuationAction As Action(Of Task(Of TResult))) As Task
Parâmetros
Uma ação a ser executada quando o Task<TResult> antecedente é concluído.An action to run when the antecedent Task<TResult> completes. Quando executado, o delegado passará a tarefa concluída como um argumento.When run, the delegate will be passed the completed task as an argument.
Retornos
Uma nova tarefa de continuação.A new continuation task.
Exceções
O Task<TResult> foi descartado.The Task<TResult> has been disposed.
O argumento continuationAction
é null
.The continuationAction
argument is null
.
Exemplos
O exemplo a seguir cria uma tarefa Antecedent que usa Sieve de Eratosthenes para calcular os números primos entre 1 e um valor inserido pelo usuário.The following example creates an antecedent task that uses the Sieve of Eratosthenes to calculate the prime numbers between 1 and a value entered by the user. Uma matriz é usada para manter informações sobre os números primos.An array is used to hold information about the prime numbers. O índice de matriz representa o número e o valor do elemento indica se esse número é composto (seu valor é true
) ou primo (seu valor é false
).The array index represents the number, and the element's value indicates whether that number is composite (its value is true
) or prime (its value is false
). Essa tarefa é passada para uma tarefa de continuação, que é responsável por extrair os números primos da matriz de inteiros e exibi-los.This task is then passed to a continuation task, which is responsible for extracting the prime numbers from the integer array and displaying them.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
public class Example
{
public static void Main(string[] args)
{
int upperBound = args.Length >= 1 ? Int32.Parse(args[0]) : 200;
var t1 = Task.Run(() => { // True = composite.
// False = prime.
bool[] values = new bool[upperBound + 1];
for (int ctr = 2; ctr <= (int) Math.Sqrt(upperBound); ctr++) {
if (values[ctr] == false) {
for (int product = ctr * ctr; product <= upperBound;
product = product + ctr)
values[product] = true;
}
}
return values; });
var t2 = t1.ContinueWith( (antecedent) => { // Create a list of prime numbers.
var primes = new List<int>();
bool[] numbers = antecedent.Result;
string output = String.Empty;
for (int ctr = 1; ctr <= numbers.GetUpperBound(0); ctr++)
if (numbers[ctr] == false)
primes.Add(ctr);
// Create the output string.
for (int ctr = 0; ctr < primes.Count; ctr++) {
output += primes[ctr].ToString("N0");
if (ctr < primes.Count - 1)
output += ", ";
if ((ctr + 1) % 8 == 0)
output += Environment.NewLine;
}
//Display the result.
Console.WriteLine("Prime numbers from 1 to {0}:\n",
upperBound);
Console.WriteLine(output);
});
try {
t2.Wait();
}
catch (AggregateException ae) {
foreach (var e in ae.InnerExceptions)
Console.WriteLine("{0}: {1}", e.GetType().Name, e.Message);
}
}
}
// The example displays output like the following:
// Prime numbers from 1 to 400:
//
// 1, 2, 3, 5, 7, 11, 13, 17,
// 19, 23, 29, 31, 37, 41, 43, 47,
// 53, 59, 61, 67, 71, 73, 79, 83,
// 89, 97, 101, 103, 107, 109, 113, 127,
// 131, 137, 139, 149, 151, 157, 163, 167,
// 173, 179, 181, 191, 193, 197, 199, 211,
// 223, 227, 229, 233, 239, 241, 251, 257,
// 263, 269, 271, 277, 281, 283, 293, 307,
// 311, 313, 317, 331, 337, 347, 349, 353,
// 359, 367, 373, 379, 383, 389, 397, 401
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks
Module Example
Public Sub Main(args() As String)
Dim upperBound As Integer = If(args.Length >= 1, CInt(args(0)), 200)
Dim t1 = Task.Run(Function()
' True = composite.
' False = prime.
Dim values(upperBound) As Boolean
For ctr = 2 To CInt(Math.Sqrt(upperBound))
If values(ctr) = False Then
For product = ctr * ctr To upperBound Step ctr
values(product) = True
Next
End If
Next
Return values
End Function)
Dim t2 = t1.ContinueWith(Sub(antecedent)
' Create a list of prime numbers.
Dim primes As New List(Of Integer)()
Dim numbers As Boolean() = antecedent.Result
Dim output As String = String.Empty
For ctr As Integer = 1 To numbers.GetUpperBound(0)
If numbers(ctr) = False Then primes.Add(ctr)
Next
' Create the output string.
For ctr As Integer = 0 To primes.Count - 1
output += primes(ctr).ToString("N0")
If ctr < primes.Count - 1 Then output += ", "
If (ctr + 1) Mod 8 = 0 Then output += vbCrLf
Next
'Display the result.
Console.WriteLine("Prime numbers from 1 to {0}:{1}",
upperBound, vbCrLf)
Console.WriteLine(output)
End Sub)
Try
t2.Wait()
Catch ae As AggregateException
For Each e In ae.InnerExceptions
Console.WriteLine("{0}: {1}", e.GetType().Name, e.Message)
Next
End Try
End Sub
End Module
' The example displays output like the following:
' Prime numbers from 1 to 400:
'
' 1, 2, 3, 5, 7, 11, 13, 17,
' 19, 23, 29, 31, 37, 41, 43, 47,
' 53, 59, 61, 67, 71, 73, 79, 83,
' 89, 97, 101, 103, 107, 109, 113, 127,
' 131, 137, 139, 149, 151, 157, 163, 167,
' 173, 179, 181, 191, 193, 197, 199, 211,
' 223, 227, 229, 233, 239, 241, 251, 257,
' 263, 269, 271, 277, 281, 283, 293, 307,
' 311, 313, 317, 331, 337, 347, 349, 353,
' 359, 367, 373, 379, 383, 389, 397, 401
' If cancellation is requested, the example displays output like the following:
' The operation was cancelled.
Comentários
O retornado Task não será agendado para execução até que a tarefa atual seja concluída, seja ela concluída devido à conclusão com êxito, com falha devido a uma exceção sem tratamento ou que seja encerrada antecipadamente devido a ser cancelada.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 being canceled.
Confira também
- Biblioteca de tarefas paralelas (TPL)Task Parallel Library (TPL)
- Programação assíncrona baseada em tarefasTask-based Asynchronous Programming
- Encadeando tarefas com tarefas de continuaçãoChaining Tasks by Using Continuation Tasks
Aplica-se a
ContinueWith(Action<Task<TResult>>, TaskScheduler)
Criará uma continuação executada de forma assíncrona quando o Task<TResult> de destino for concluído.Creates a continuation that executes asynchronously when the target Task<TResult> completes.
public:
System::Threading::Tasks::Task ^ ContinueWith(Action<System::Threading::Tasks::Task<TResult> ^> ^ continuationAction, System::Threading::Tasks::TaskScheduler ^ scheduler);
public System.Threading.Tasks.Task ContinueWith (Action<System.Threading.Tasks.Task<TResult>> continuationAction, System.Threading.Tasks.TaskScheduler scheduler);
override this.ContinueWith : Action<System.Threading.Tasks.Task<'Result>> * System.Threading.Tasks.TaskScheduler -> System.Threading.Tasks.Task
Public Function ContinueWith (continuationAction As Action(Of Task(Of TResult)), scheduler As TaskScheduler) As Task
Parâmetros
Uma ação a ser executada quando o Task<TResult> for concluído.An action to run when the Task<TResult> completes. Quando executado, o delegado passará a tarefa concluída como um argumento.When run, the delegate will be passed the completed task as an argument.
- scheduler
- TaskScheduler
O TaskScheduler a ser associado à tarefa de continuação e a ser usado para sua execução.The TaskScheduler to associate with the continuation task and to use for its execution.
Retornos
Um novo Task de continuação.A new continuation Task.
Exceções
O Task<TResult> foi descartado.The Task<TResult> has been disposed.
O argumento continuationAction
é null
.The continuationAction
argument is null
.
- ou --or-
O argumento scheduler
é null
.The scheduler
argument is null
.
Comentários
O retornado Task não será agendado para execução até que a tarefa atual seja concluída, seja ela concluída devido à conclusão com êxito, com falha devido a uma exceção sem tratamento ou que seja encerrada antecipadamente devido a ser cancelada.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.
Confira também
- Biblioteca de tarefas paralelas (TPL)Task Parallel Library (TPL)
- Programação assíncrona baseada em tarefasTask-based Asynchronous Programming
- Encadeando tarefas com tarefas de continuaçãoChaining Tasks by Using Continuation Tasks
Aplica-se a
ContinueWith<TNewResult>(Func<Task<TResult>,Object,TNewResult>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler)
Criará uma continuação executada quando o Task<TResult> de destino for concluído.Creates a continuation that executes when the target Task<TResult> completes.
public:
generic <typename TNewResult>
System::Threading::Tasks::Task<TNewResult> ^ ContinueWith(Func<System::Threading::Tasks::Task<TResult> ^, System::Object ^, TNewResult> ^ continuationFunction, System::Object ^ state, System::Threading::CancellationToken cancellationToken, System::Threading::Tasks::TaskContinuationOptions continuationOptions, System::Threading::Tasks::TaskScheduler ^ scheduler);
public System.Threading.Tasks.Task<TNewResult> ContinueWith<TNewResult> (Func<System.Threading.Tasks.Task<TResult>,object,TNewResult> continuationFunction, object state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskContinuationOptions continuationOptions, System.Threading.Tasks.TaskScheduler scheduler);
public System.Threading.Tasks.Task<TNewResult> ContinueWith<TNewResult> (Func<System.Threading.Tasks.Task<TResult>,object?,TNewResult> continuationFunction, object? state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskContinuationOptions continuationOptions, System.Threading.Tasks.TaskScheduler scheduler);
override this.ContinueWith : Func<System.Threading.Tasks.Task<'Result>, obj, 'NewResult> * obj * System.Threading.CancellationToken * System.Threading.Tasks.TaskContinuationOptions * System.Threading.Tasks.TaskScheduler -> System.Threading.Tasks.Task<'NewResult>
Public Function ContinueWith(Of TNewResult) (continuationFunction As Func(Of Task(Of TResult), Object, TNewResult), state As Object, cancellationToken As CancellationToken, continuationOptions As TaskContinuationOptions, scheduler As TaskScheduler) As Task(Of TNewResult)
Parâmetros de tipo
- TNewResult
O tipo do resultado produzido pela continuação.The type of the result produced by the continuation.
Parâmetros
Uma função a ser executada quando o Task<TResult> for concluído.A function to run when the Task<TResult> completes. Quando a ação for executada, a tarefa concluída e o objeto de estado fornecido pelo chamador serão passados como argumentos ao delegado.When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.
- state
- Object
Um objeto que representa os dados a serem usados pela função de continuação.An object representing data to be used by the continuation function.
- cancellationToken
- CancellationToken
O CancellationToken que será atribuído a nova tarefa.The CancellationToken that will be assigned to the new task.
- continuationOptions
- TaskContinuationOptions
Opções para quando a continuação é agendada e como ela se comporta.Options for when the continuation is scheduled and how it behaves. Isso inclui critérios como OnlyOnCanceled, além de opções de execução como ExecuteSynchronously.This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.
- scheduler
- TaskScheduler
O TaskScheduler a ser associado à tarefa de continuação e a ser usado para sua execução.The TaskScheduler to associate with the continuation task and to use for its execution.
Retornos
- Task<TNewResult>
Um novo Task<TResult> de continuação.A new continuation Task<TResult>.
Exceções
O argumento scheduler
é null
.The scheduler
argument is null
.
O argumento continuationOptions
especifica um valor inválido para TaskContinuationOptions.The continuationOptions
argument specifies an invalid value for TaskContinuationOptions.
O CancellationToken fornecido já foi descartado.The provided CancellationToken has already been disposed.
Comentários
O retornado Task<TResult> não será agendado para execução até que a tarefa atual seja concluída, seja ela concluída devido à conclusão com êxito, com falha devido a uma exceção sem tratamento ou que seja encerrada antecipadamente devido a ser cancelada.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.
O continuationFunction
, quando executado, deve retornar um Task<TResult> .The continuationFunction
, when executed, should return a Task<TResult>. O estado de conclusão dessa tarefa será transferido para a tarefa retornada pela Task<TResult>.ContinueWith chamada.This task's completion state will be transferred to the task returned from the Task<TResult>.ContinueWith call.
Confira também
Aplica-se a
ContinueWith<TNewResult>(Func<Task<TResult>,TNewResult>, CancellationToken, TaskContinuationOptions, TaskScheduler)
Cria uma continuação executada de acordo com a condição especificada em continuationOptions
.Creates a continuation that executes according the condition specified in continuationOptions
.
public:
generic <typename TNewResult>
System::Threading::Tasks::Task<TNewResult> ^ ContinueWith(Func<System::Threading::Tasks::Task<TResult> ^, TNewResult> ^ continuationFunction, System::Threading::CancellationToken cancellationToken, System::Threading::Tasks::TaskContinuationOptions continuationOptions, System::Threading::Tasks::TaskScheduler ^ scheduler);
public System.Threading.Tasks.Task<TNewResult> ContinueWith<TNewResult> (Func<System.Threading.Tasks.Task<TResult>,TNewResult> continuationFunction, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskContinuationOptions continuationOptions, System.Threading.Tasks.TaskScheduler scheduler);
override this.ContinueWith : Func<System.Threading.Tasks.Task<'Result>, 'NewResult> * System.Threading.CancellationToken * System.Threading.Tasks.TaskContinuationOptions * System.Threading.Tasks.TaskScheduler -> System.Threading.Tasks.Task<'NewResult>
Public Function ContinueWith(Of TNewResult) (continuationFunction As Func(Of Task(Of TResult), TNewResult), cancellationToken As CancellationToken, continuationOptions As TaskContinuationOptions, scheduler As TaskScheduler) As Task(Of TNewResult)
Parâmetros de tipo
- TNewResult
O tipo do resultado produzido pela continuação.The type of the result produced by the continuation.
Parâmetros
Uma função a ser executada de acordo com a condição especificada em continuationOptions
.A function to run according the condition specified in continuationOptions
.
Quando executado, o delegado passará essa tarefa concluída como um argumento.When run, the delegate will be passed as an argument this completed task.
- cancellationToken
- CancellationToken
O CancellationToken que será atribuído a nova tarefa.The CancellationToken that will be assigned to the new task.
- continuationOptions
- TaskContinuationOptions
Opções para quando a continuação é agendada e como ela se comporta.Options for when the continuation is scheduled and how it behaves. Isso inclui critérios como OnlyOnCanceled, além de opções de execução como ExecuteSynchronously.This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.
- scheduler
- TaskScheduler
O TaskScheduler a ser associado à tarefa de continuação e a ser usado para sua execução.The TaskScheduler to associate with the continuation task and to use for its execution.
Retornos
- Task<TNewResult>
Um novo Task<TResult> de continuação.A new continuation Task<TResult>.
Exceções
O Task<TResult> foi descartado.The Task<TResult> has been disposed.
- ou --or-
O CancellationTokenSource que criou cancellationToken
já foi descartado.The CancellationTokenSource that created cancellationToken
has already been disposed.
O argumento continuationFunction
é null
.The continuationFunction
argument is null
.
- ou --or-
O argumento scheduler
é null
.The scheduler
argument is null
.
O argumento continuationOptions
especifica um valor inválido para TaskContinuationOptions.The continuationOptions
argument specifies an invalid value for TaskContinuationOptions.
Comentários
O retornado Task<TResult> não será agendado para execução até que a tarefa atual seja concluída, seja ela concluída devido à conclusão com êxito, com falha devido a uma exceção sem tratamento ou que seja encerrada antecipadamente devido a ser cancelada.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.
O continuationFunction
, quando executado, deve retornar um Task<TResult> .The continuationFunction
, when executed, should return a Task<TResult>.
Confira também
- Biblioteca de tarefas paralelas (TPL)Task Parallel Library (TPL)
- Programação assíncrona baseada em tarefasTask-based Asynchronous Programming
- Encadeando tarefas com tarefas de continuaçãoChaining Tasks by Using Continuation Tasks
Aplica-se a
ContinueWith<TNewResult>(Func<Task<TResult>,Object,TNewResult>, Object, TaskScheduler)
Criará uma continuação executada quando o Task<TResult> de destino for concluído.Creates a continuation that executes when the target Task<TResult> completes.
public:
generic <typename TNewResult>
System::Threading::Tasks::Task<TNewResult> ^ ContinueWith(Func<System::Threading::Tasks::Task<TResult> ^, System::Object ^, TNewResult> ^ continuationFunction, System::Object ^ state, System::Threading::Tasks::TaskScheduler ^ scheduler);
public System.Threading.Tasks.Task<TNewResult> ContinueWith<TNewResult> (Func<System.Threading.Tasks.Task<TResult>,object,TNewResult> continuationFunction, object state, System.Threading.Tasks.TaskScheduler scheduler);
public System.Threading.Tasks.Task<TNewResult> ContinueWith<TNewResult> (Func<System.Threading.Tasks.Task<TResult>,object?,TNewResult> continuationFunction, object? state, System.Threading.Tasks.TaskScheduler scheduler);
override this.ContinueWith : Func<System.Threading.Tasks.Task<'Result>, obj, 'NewResult> * obj * System.Threading.Tasks.TaskScheduler -> System.Threading.Tasks.Task<'NewResult>
Public Function ContinueWith(Of TNewResult) (continuationFunction As Func(Of Task(Of TResult), Object, TNewResult), state As Object, scheduler As TaskScheduler) As Task(Of TNewResult)
Parâmetros de tipo
- TNewResult
O tipo do resultado produzido pela continuação.The type of the result produced by the continuation.
Parâmetros
Uma função a ser executada quando o Task<TResult> for concluído.A function to run when the Task<TResult> completes. Quando executada, a tarefa concluída e o objeto de estado fornecido pelo chamador serão passados como argumentos ao delegado.When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.
- state
- Object
Um objeto que representa os dados a serem usados pela função de continuação.An object representing data to be used by the continuation function.
- scheduler
- TaskScheduler
O TaskScheduler a ser associado à tarefa de continuação e a ser usado para sua execução.The TaskScheduler to associate with the continuation task and to use for its execution.
Retornos
- Task<TNewResult>
Um novo Task<TResult> de continuação.A new continuation Task<TResult>.
Exceções
O argumento scheduler
é null
.The scheduler
argument is null
.
Comentários
O retornado Task<TResult> não será agendado para execução até que a tarefa atual seja concluída, seja ela concluída devido à conclusão com êxito, com falha devido a uma exceção sem tratamento ou que seja encerrada antecipadamente devido a ser cancelada.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.
Confira também
Aplica-se a
ContinueWith<TNewResult>(Func<Task<TResult>,Object,TNewResult>, Object, TaskContinuationOptions)
Criará uma continuação executada quando o Task<TResult> de destino for concluído.Creates a continuation that executes when the target Task<TResult> completes.
public:
generic <typename TNewResult>
System::Threading::Tasks::Task<TNewResult> ^ ContinueWith(Func<System::Threading::Tasks::Task<TResult> ^, System::Object ^, TNewResult> ^ continuationFunction, System::Object ^ state, System::Threading::Tasks::TaskContinuationOptions continuationOptions);
public System.Threading.Tasks.Task<TNewResult> ContinueWith<TNewResult> (Func<System.Threading.Tasks.Task<TResult>,object,TNewResult> continuationFunction, object state, System.Threading.Tasks.TaskContinuationOptions continuationOptions);
public System.Threading.Tasks.Task<TNewResult> ContinueWith<TNewResult> (Func<System.Threading.Tasks.Task<TResult>,object?,TNewResult> continuationFunction, object? state, System.Threading.Tasks.TaskContinuationOptions continuationOptions);
override this.ContinueWith : Func<System.Threading.Tasks.Task<'Result>, obj, 'NewResult> * obj * System.Threading.Tasks.TaskContinuationOptions -> System.Threading.Tasks.Task<'NewResult>
Public Function ContinueWith(Of TNewResult) (continuationFunction As Func(Of Task(Of TResult), Object, TNewResult), state As Object, continuationOptions As TaskContinuationOptions) As Task(Of TNewResult)
Parâmetros de tipo
- TNewResult
O tipo do resultado produzido pela continuação.The type of the result produced by the continuation.
Parâmetros
Uma função a ser executada quando o Task<TResult> for concluído.A function to run when the Task<TResult> completes. Quando a ação for executada, a tarefa concluída e o objeto de estado fornecido pelo chamador serão passados como argumentos ao delegado.When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.
- state
- Object
Um objeto que representa os dados a serem usados pela função de continuação.An object representing data to be used by the continuation function.
- continuationOptions
- TaskContinuationOptions
Opções para quando a continuação é agendada e como ela se comporta.Options for when the continuation is scheduled and how it behaves. Isso inclui critérios como OnlyOnCanceled, além de opções de execução como ExecuteSynchronously.This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.
Retornos
- Task<TNewResult>
Um novo Task<TResult> de continuação.A new continuation Task<TResult>.
Exceções
O argumento continuationFunction
é null
.The continuationFunction
argument is null
.
O argumento continuationOptions
especifica um valor inválido para TaskContinuationOptions.The continuationOptions
argument specifies an invalid value for TaskContinuationOptions.
Comentários
O retornado Task<TResult> não será agendado para execução até que a tarefa atual seja concluída, seja ela concluída devido à conclusão com êxito, com falha devido a uma exceção sem tratamento ou que seja encerrada antecipadamente devido a ser cancelada.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.
O continuationFunction
, quando executado, deve retornar um Task<TResult> .The continuationFunction
, when executed, should return a Task<TResult>. O estado de conclusão dessa tarefa será transferido para a tarefa retornada pela chamada ContinueWith.This task's completion state will be transferred to the task returned from the ContinueWith call.
Confira também
Aplica-se a
ContinueWith<TNewResult>(Func<Task<TResult>,Object,TNewResult>, Object, CancellationToken)
Criará uma continuação executada quando o Task<TResult> de destino for concluído.Creates a continuation that executes when the target Task<TResult> completes.
public:
generic <typename TNewResult>
System::Threading::Tasks::Task<TNewResult> ^ ContinueWith(Func<System::Threading::Tasks::Task<TResult> ^, System::Object ^, TNewResult> ^ continuationFunction, System::Object ^ state, System::Threading::CancellationToken cancellationToken);
public System.Threading.Tasks.Task<TNewResult> ContinueWith<TNewResult> (Func<System.Threading.Tasks.Task<TResult>,object,TNewResult> continuationFunction, object state, System.Threading.CancellationToken cancellationToken);
public System.Threading.Tasks.Task<TNewResult> ContinueWith<TNewResult> (Func<System.Threading.Tasks.Task<TResult>,object?,TNewResult> continuationFunction, object? state, System.Threading.CancellationToken cancellationToken);
override this.ContinueWith : Func<System.Threading.Tasks.Task<'Result>, obj, 'NewResult> * obj * System.Threading.CancellationToken -> System.Threading.Tasks.Task<'NewResult>
Public Function ContinueWith(Of TNewResult) (continuationFunction As Func(Of Task(Of TResult), Object, TNewResult), state As Object, cancellationToken As CancellationToken) As Task(Of TNewResult)
Parâmetros de tipo
- TNewResult
O tipo do resultado produzido pela continuação.The type of the result produced by the continuation.
Parâmetros
Uma função a ser executada quando o Task<TResult> for concluído.A function to run when the Task<TResult> completes. Quando executada, a tarefa concluída e o objeto de estado fornecido pelo chamador serão passados como argumentos ao delegado.When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.
- state
- Object
Um objeto que representa os dados a serem usados pela função de continuação.An object representing data to be used by the continuation function.
- cancellationToken
- CancellationToken
O CancellationToken que será atribuído a nova tarefa.The CancellationToken that will be assigned to the new task.
Retornos
- Task<TNewResult>
Um novo Task<TResult> de continuação.A new continuation Task<TResult>.
Exceções
O argumento continuationFunction
é null
.The continuationFunction
argument is null
.
O CancellationToken fornecido já foi descartado.The provided CancellationToken has already been disposed.
Comentários
O retornado Task<TResult> não será agendado para execução até que a tarefa atual seja concluída, seja ela concluída devido à conclusão com êxito, com falha devido a uma exceção sem tratamento ou que seja encerrada antecipadamente devido a ser cancelada.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.
Confira também
Aplica-se a
ContinueWith<TNewResult>(Func<Task<TResult>,TNewResult>, TaskContinuationOptions)
Cria uma continuação executada de acordo com a condição especificada em continuationOptions
.Creates a continuation that executes according the condition specified in continuationOptions
.
public:
generic <typename TNewResult>
System::Threading::Tasks::Task<TNewResult> ^ ContinueWith(Func<System::Threading::Tasks::Task<TResult> ^, TNewResult> ^ continuationFunction, System::Threading::Tasks::TaskContinuationOptions continuationOptions);
public System.Threading.Tasks.Task<TNewResult> ContinueWith<TNewResult> (Func<System.Threading.Tasks.Task<TResult>,TNewResult> continuationFunction, System.Threading.Tasks.TaskContinuationOptions continuationOptions);
override this.ContinueWith : Func<System.Threading.Tasks.Task<'Result>, 'NewResult> * System.Threading.Tasks.TaskContinuationOptions -> System.Threading.Tasks.Task<'NewResult>
Public Function ContinueWith(Of TNewResult) (continuationFunction As Func(Of Task(Of TResult), TNewResult), continuationOptions As TaskContinuationOptions) As Task(Of TNewResult)
Parâmetros de tipo
- TNewResult
O tipo do resultado produzido pela continuação.The type of the result produced by the continuation.
Parâmetros
Uma função a ser executada de acordo com a condição especificada em continuationOptions
.A function to run according the condition specified in continuationOptions
.
Quando executado, o delegado passará a tarefa concluída como um argumento.When run, the delegate will be passed the completed task as an argument.
- continuationOptions
- TaskContinuationOptions
Opções para quando a continuação é agendada e como ela se comporta.Options for when the continuation is scheduled and how it behaves. Isso inclui critérios como OnlyOnCanceled, além de opções de execução como ExecuteSynchronously.This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.
Retornos
- Task<TNewResult>
Um novo Task<TResult> de continuação.A new continuation Task<TResult>.
Exceções
O Task<TResult> foi descartado.The Task<TResult> has been disposed.
O argumento continuationFunction
é null
.The continuationFunction
argument is null
.
O argumento continuationOptions
especifica um valor inválido para TaskContinuationOptions.The continuationOptions
argument specifies an invalid value for TaskContinuationOptions.
Comentários
O retornado Task<TResult> não será agendado para execução até que a tarefa atual seja concluída, seja ela concluída devido à conclusão com êxito, com falha devido a uma exceção sem tratamento ou que seja encerrada antecipadamente devido a ser cancelada.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.
O continuationFunction
, quando executado, deve retornar um Task<TResult> .The continuationFunction
, when executed, should return a Task<TResult>.
Confira também
- Biblioteca de tarefas paralelas (TPL)Task Parallel Library (TPL)
- Programação assíncrona baseada em tarefasTask-based Asynchronous Programming
- Encadeando tarefas com tarefas de continuaçãoChaining Tasks by Using Continuation Tasks
Aplica-se a
ContinueWith<TNewResult>(Func<Task<TResult>,TNewResult>, CancellationToken)
Criará uma continuação executada de forma assíncrona quando o Task<TResult> de destino for concluído.Creates a continuation that executes asynchronously when the target Task<TResult> completes.
public:
generic <typename TNewResult>
System::Threading::Tasks::Task<TNewResult> ^ ContinueWith(Func<System::Threading::Tasks::Task<TResult> ^, TNewResult> ^ continuationFunction, System::Threading::CancellationToken cancellationToken);
public System.Threading.Tasks.Task<TNewResult> ContinueWith<TNewResult> (Func<System.Threading.Tasks.Task<TResult>,TNewResult> continuationFunction, System.Threading.CancellationToken cancellationToken);
override this.ContinueWith : Func<System.Threading.Tasks.Task<'Result>, 'NewResult> * System.Threading.CancellationToken -> System.Threading.Tasks.Task<'NewResult>
Public Function ContinueWith(Of TNewResult) (continuationFunction As Func(Of Task(Of TResult), TNewResult), cancellationToken As CancellationToken) As Task(Of TNewResult)
Parâmetros de tipo
- TNewResult
O tipo do resultado produzido pela continuação.The type of the result produced by the continuation.
Parâmetros
Uma função a ser executada quando o Task<TResult> for concluído.A function to run when the Task<TResult> completes. Quando executado, o delegado passará a tarefa concluída como um argumento.When run, the delegate will be passed the completed task as an argument.
- cancellationToken
- CancellationToken
O CancellationToken que será atribuído a nova tarefa.The CancellationToken that will be assigned to the new task.
Retornos
- Task<TNewResult>
Um novo Task<TResult> de continuação.A new continuation Task<TResult>.
Exceções
O Task<TResult> foi descartado.The Task<TResult> has been disposed.
- ou --or-
O CancellationTokenSource que criou cancellationToken
já foi descartado.The CancellationTokenSource that created cancellationToken
has already been disposed.
O argumento continuationFunction
é null
.The continuationFunction
argument is null
.
Comentários
O retornado Task<TResult> não será agendado para execução até que a tarefa atual seja concluída, seja ela concluída devido à conclusão com êxito, com falha devido a uma exceção sem tratamento ou que seja encerrada antecipadamente devido a ser cancelada.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.
Confira também
- Biblioteca de tarefas paralelas (TPL)Task Parallel Library (TPL)
- Programação assíncrona baseada em tarefasTask-based Asynchronous Programming
- Encadeando tarefas com tarefas de continuaçãoChaining Tasks by Using Continuation Tasks
Aplica-se a
ContinueWith<TNewResult>(Func<Task<TResult>,Object,TNewResult>, Object)
Criará uma continuação executada quando o Task<TResult> de destino for concluído.Creates a continuation that executes when the target Task<TResult> completes.
public:
generic <typename TNewResult>
System::Threading::Tasks::Task<TNewResult> ^ ContinueWith(Func<System::Threading::Tasks::Task<TResult> ^, System::Object ^, TNewResult> ^ continuationFunction, System::Object ^ state);
public System.Threading.Tasks.Task<TNewResult> ContinueWith<TNewResult> (Func<System.Threading.Tasks.Task<TResult>,object,TNewResult> continuationFunction, object state);
public System.Threading.Tasks.Task<TNewResult> ContinueWith<TNewResult> (Func<System.Threading.Tasks.Task<TResult>,object?,TNewResult> continuationFunction, object? state);
override this.ContinueWith : Func<System.Threading.Tasks.Task<'Result>, obj, 'NewResult> * obj -> System.Threading.Tasks.Task<'NewResult>
Public Function ContinueWith(Of TNewResult) (continuationFunction As Func(Of Task(Of TResult), Object, TNewResult), state As Object) As Task(Of TNewResult)
Parâmetros de tipo
- TNewResult
O tipo do resultado produzido pela continuação.The type of the result produced by the continuation.
Parâmetros
Uma função a ser executada quando o Task<TResult> for concluído.A function to run when the Task<TResult> completes. Quando executada, a tarefa concluída e o objeto de estado fornecido pelo chamador serão passados como argumentos ao delegado.When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.
- state
- Object
Um objeto que representa os dados a serem usados pela função de continuação.An object representing data to be used by the continuation function.
Retornos
- Task<TNewResult>
Um novo Task<TResult> de continuação.A new continuation Task<TResult>.
Exceções
O argumento continuationFunction
é null
.The continuationFunction
argument is null
.
Exemplos
O exemplo a seguir cria uma cadeia de tarefas de continuação.The following example creates a chain of continuation tasks. Cada tarefa fornece a hora atual, um DateTime objeto, para o argumento de estado do ContinueWith(Action<Task,Object>, Object) método.Each task provides the current time, a DateTime object, for the state argument of the ContinueWith(Action<Task,Object>, Object) method. Cada DateTime valor representa a hora em que a tarefa de continuação é criada.Each DateTime value represents the time at which the continue task is created. Cada tarefa produz como resultado um segundo DateTime valor que representa a hora em que a tarefa é concluída.Each task produces as its result a second DateTime value that represents the time at which the task finishes. Após a conclusão de todas as tarefas, o exemplo exibe a data e as horas em que cada tarefa de continuação é iniciada e concluída.After all tasks finish, the example displays the date and times at which each continuation task starts and finishes.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
// Demonstrates how to associate state with task continuations.
class ContinuationState
{
// Simluates a lengthy operation and returns the time at which
// the operation completed.
public static DateTime DoWork()
{
// Simulate work by suspending the current thread
// for two seconds.
Thread.Sleep(2000);
// Return the current time.
return DateTime.Now;
}
static void Main(string[] args)
{
// Start a root task that performs work.
Task<DateTime> t = Task<DateTime>.Run(delegate { return DoWork(); });
// Create a chain of continuation tasks, where each task is
// followed by another task that performs work.
List<Task<DateTime>> continuations = new List<Task<DateTime>>();
for (int i = 0; i < 5; i++)
{
// Provide the current time as the state of the continuation.
t = t.ContinueWith(delegate { return DoWork(); }, DateTime.Now);
continuations.Add(t);
}
// Wait for the last task in the chain to complete.
t.Wait();
// Print the creation time of each continuation (the state object)
// and the completion time (the result of that task) to the console.
foreach (var continuation in continuations)
{
DateTime start = (DateTime)continuation.AsyncState;
DateTime end = continuation.Result;
Console.WriteLine("Task was created at {0} and finished at {1}.",
start.TimeOfDay, end.TimeOfDay);
}
}
}
/* Sample output:
Task was created at 10:56:21.1561762 and finished at 10:56:25.1672062.
Task was created at 10:56:21.1610677 and finished at 10:56:27.1707646.
Task was created at 10:56:21.1610677 and finished at 10:56:29.1743230.
Task was created at 10:56:21.1610677 and finished at 10:56:31.1779883.
Task was created at 10:56:21.1610677 and finished at 10:56:33.1837083.
*/
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks
' Demonstrates how to associate state with task continuations.
Public Module ContinuationState
' Simluates a lengthy operation and returns the time at which
' the operation completed.
Public Function DoWork() As Date
' Simulate work by suspending the current thread
' for two seconds.
Thread.Sleep(2000)
' Return the current time.
Return Date.Now
End Function
Public Sub Main()
' Start a root task that performs work.
Dim t As Task(Of Date) = Task(Of Date).Run(Function() DoWork())
' Create a chain of continuation tasks, where each task is
' followed by another task that performs work.
Dim continuations As New List(Of Task(Of DateTime))()
For i As Integer = 0 To 4
' Provide the current time as the state of the continuation.
t = t.ContinueWith(Function(antecedent, state) DoWork(), DateTime.Now)
continuations.Add(t)
Next
' Wait for the last task in the chain to complete.
t.Wait()
' Display the creation time of each continuation (the state object)
' and the completion time (the result of that task) to the console.
For Each continuation In continuations
Dim start As DateTime = CDate(continuation.AsyncState)
Dim [end] As DateTime = continuation.Result
Console.WriteLine("Task was created at {0} and finished at {1}.",
start.TimeOfDay, [end].TimeOfDay)
Next
End Sub
End Module
' The example displays output like the following:
' Task was created at 10:56:21.1561762 and finished at 10:56:25.1672062.
' Task was created at 10:56:21.1610677 and finished at 10:56:27.1707646.
' Task was created at 10:56:21.1610677 and finished at 10:56:29.1743230.
' Task was created at 10:56:21.1610677 and finished at 10:56:31.1779883.
' Task was created at 10:56:21.1610677 and finished at 10:56:33.1837083.
Comentários
O retornado Task<TResult> não será agendado para execução até que a tarefa atual seja concluída, seja ela concluída devido à conclusão com êxito, com falha devido a uma exceção sem tratamento ou que seja encerrada antecipadamente devido a ser cancelada.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.
Confira também
Aplica-se a
ContinueWith<TNewResult>(Func<Task<TResult>,TNewResult>)
Criará uma continuação executada de forma assíncrona quando o Task<TResult> de destino for concluído.Creates a continuation that executes asynchronously when the target Task<TResult> completes.
public:
generic <typename TNewResult>
System::Threading::Tasks::Task<TNewResult> ^ ContinueWith(Func<System::Threading::Tasks::Task<TResult> ^, TNewResult> ^ continuationFunction);
public System.Threading.Tasks.Task<TNewResult> ContinueWith<TNewResult> (Func<System.Threading.Tasks.Task<TResult>,TNewResult> continuationFunction);
override this.ContinueWith : Func<System.Threading.Tasks.Task<'Result>, 'NewResult> -> System.Threading.Tasks.Task<'NewResult>
Public Function ContinueWith(Of TNewResult) (continuationFunction As Func(Of Task(Of TResult), TNewResult)) As Task(Of TNewResult)
Parâmetros de tipo
- TNewResult
O tipo do resultado produzido pela continuação.The type of the result produced by the continuation.
Parâmetros
Uma função a ser executada quando o Task<TResult> for concluído.A function to run when the Task<TResult> completes. Quando executado, o delegado passará a tarefa concluída como um argumento.When run, the delegate will be passed the completed task as an argument.
Retornos
- Task<TNewResult>
Um novo Task<TResult> de continuação.A new continuation Task<TResult>.
Exceções
O Task<TResult> foi descartado.The Task<TResult> has been disposed.
O argumento continuationFunction
é null
.The continuationFunction
argument is null
.
Comentários
O retornado Task<TResult> não será agendado para execução até que a tarefa atual seja concluída, seja ela concluída devido à conclusão com êxito, com falha devido a uma exceção sem tratamento ou que seja encerrada antecipadamente devido a ser cancelada.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.
Confira também
- Biblioteca de tarefas paralelas (TPL)Task Parallel Library (TPL)
- Programação assíncrona baseada em tarefasTask-based Asynchronous Programming
- Encadeando tarefas com tarefas de continuaçãoChaining Tasks by Using Continuation Tasks
Aplica-se a
ContinueWith<TNewResult>(Func<Task<TResult>,TNewResult>, TaskScheduler)
Criará uma continuação executada de forma assíncrona quando o Task<TResult> de destino for concluído.Creates a continuation that executes asynchronously when the target Task<TResult> completes.
public:
generic <typename TNewResult>
System::Threading::Tasks::Task<TNewResult> ^ ContinueWith(Func<System::Threading::Tasks::Task<TResult> ^, TNewResult> ^ continuationFunction, System::Threading::Tasks::TaskScheduler ^ scheduler);
public System.Threading.Tasks.Task<TNewResult> ContinueWith<TNewResult> (Func<System.Threading.Tasks.Task<TResult>,TNewResult> continuationFunction, System.Threading.Tasks.TaskScheduler scheduler);
override this.ContinueWith : Func<System.Threading.Tasks.Task<'Result>, 'NewResult> * System.Threading.Tasks.TaskScheduler -> System.Threading.Tasks.Task<'NewResult>
Public Function ContinueWith(Of TNewResult) (continuationFunction As Func(Of Task(Of TResult), TNewResult), scheduler As TaskScheduler) As Task(Of TNewResult)
Parâmetros de tipo
- TNewResult
O tipo do resultado produzido pela continuação.The type of the result produced by the continuation.
Parâmetros
Uma função a ser executada quando o Task<TResult> for concluído.A function to run when the Task<TResult> completes. Quando executado, o delegado passará a tarefa concluída como um argumento.When run, the delegate will be passed the completed task as an argument.
- scheduler
- TaskScheduler
O TaskScheduler a ser associado à tarefa de continuação e a ser usado para sua execução.The TaskScheduler to associate with the continuation task and to use for its execution.
Retornos
- Task<TNewResult>
Um novo Task<TResult> de continuação.A new continuation Task<TResult>.
Exceções
O Task<TResult> foi descartado.The Task<TResult> has been disposed.
O argumento continuationFunction
é null
.The continuationFunction
argument is null
.
- ou --or-
O argumento scheduler
é null
.The scheduler
argument is null
.
Comentários
O retornado Task<TResult> não será agendado para execução até que a tarefa atual seja concluída, seja ela concluída devido à conclusão com êxito, com falha devido a uma exceção sem tratamento ou que seja encerrada antecipadamente devido a ser cancelada.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.
Confira também
- TaskScheduler
- Biblioteca de tarefas paralelas (TPL)Task Parallel Library (TPL)
- Programação assíncrona baseada em tarefasTask-based Asynchronous Programming
- Encadeando tarefas com tarefas de continuaçãoChaining Tasks by Using Continuation Tasks