Task<TResult>.ContinueWith Task<TResult>.ContinueWith Task<TResult>.ContinueWith Task<TResult>.ContinueWith Method

Definición

Crea una tarea de continuación que se ejecuta cuando se completa otra tarea.Creates a continuation task that executes when another task completes.

Sobrecargas

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

Crea una continuación que se ejecuta cuando se completa el objeto Task<TResult> de destino.Creates a continuation that executes when the target Task<TResult> completes.

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

Crea una continuación que se ejecuta según la condición especificada en continuationOptions.Creates a continuation that executes according the condition specified in continuationOptions.

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

Crea una continuación que se ejecuta cuando se completa el objeto Task<TResult> de destino.Creates a continuation that executes when the target Task<TResult> completes.

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

Crea una continuación que se ejecuta cuando se completa el objeto Task<TResult> de destino.Creates a continuation that executes when the target Task<TResult> completes.

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

Crea una continuación que se ejecuta cuando se completa el objeto Task<TResult> de destino.Creates a continuation that executes when the target Task<TResult> completes.

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

Crea una continuación que se ejecuta según la condición especificada en continuationOptions.Creates a continuation that executes according the condition specified in continuationOptions.

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

Crea una continuación que se puede cancelar y se ejecuta de forma asincrónica al completarse el parámetro Task<TResult> de destino.Creates a cancelable continuation that executes asynchronously when the target Task<TResult> completes.

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

Crea una continuación a la que se pasa información de estado y que se ejecuta cuando el objeto Task<TResult> de destino se completa.Creates a continuation that is passed state information and that executes when the target Task<TResult> completes.

ContinueWith(Action<Task<TResult>>) ContinueWith(Action<Task<TResult>>) ContinueWith(Action<Task<TResult>>) ContinueWith(Action<Task<TResult>>)

Crea una continuación que se ejecuta de manera asincrónica cuando se completa la tarea de destino.Creates a continuation that executes asynchronously when the target task completes.

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

Crea una continuación que se ejecuta de manera asincrónica cuando se completa el objeto Task<TResult> de destino.Creates a continuation that executes asynchronously when the target Task<TResult> completes.

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

Crea una continuación que se ejecuta cuando se completa el objeto Task<TResult> de destino.Creates a continuation that executes when the target Task<TResult> completes.

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

Crea una continuación que se ejecuta según la condición especificada en continuationOptions.Creates a continuation that executes according the condition specified in continuationOptions.

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

Crea una continuación que se ejecuta cuando se completa el objeto Task<TResult> de destino.Creates a continuation that executes when the target Task<TResult> completes.

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

Crea una continuación que se ejecuta cuando se completa el objeto Task<TResult> de destino.Creates a continuation that executes when the target Task<TResult> completes.

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

Crea una continuación que se ejecuta cuando se completa el objeto Task<TResult> de destino.Creates a continuation that executes when the target Task<TResult> completes.

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

Crea una continuación que se ejecuta según la condición especificada en continuationOptions.Creates a continuation that executes according the condition specified in continuationOptions.

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

Crea una continuación que se ejecuta de manera asincrónica cuando se completa el objeto Task<TResult> de destino.Creates a continuation that executes asynchronously when the target Task<TResult> completes.

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

Crea una continuación que se ejecuta cuando se completa el objeto Task<TResult> de destino.Creates a continuation that executes when the target Task<TResult> completes.

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

Crea una continuación que se ejecuta de manera asincrónica cuando se completa el objeto Task<TResult> de destino.Creates a continuation that executes asynchronously when the target Task<TResult> completes.

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

Crea una continuación que se ejecuta de manera asincrónica cuando se completa el objeto Task<TResult> de destino.Creates a continuation that executes asynchronously when the target Task<TResult> completes.

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

Crea una continuación que se ejecuta cuando se completa el objeto Task<TResult> de destino.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);
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

Parámetros

continuationAction
Action<Task<TResult>,Object>

Acción que se va a ejecutar cuando se complete el objeto Task<TResult>.An action to run when the Task<TResult> completes. Cuando se ejecute, se pasarán al delegado la tarea completada y el objeto de estado proporcionado por el llamador como argumentos.When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.

state
Object Object Object Object

Objeto que representa los datos que la acción de continuación va a usar.An object representing data to be used by the continuation action.

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

CancellationToken que se va a asignar a la nueva tarea de continuación.The CancellationToken that will be assigned to the new continuation task.

continuationOptions
TaskContinuationOptions TaskContinuationOptions TaskContinuationOptions TaskContinuationOptions

Opciones para la programación y el comportamiento de la continuación.Options for when the continuation is scheduled and how it behaves. Incluye criterios tales como OnlyOnCanceled, así como opciones de ejecución tales como ExecuteSynchronously.This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.

scheduler
TaskScheduler TaskScheduler TaskScheduler TaskScheduler

Objeto TaskScheduler que se va a asociar a la tarea de continuación y se va a usar para su ejecución.The TaskScheduler to associate with the continuation task and to use for its execution.

Devoluciones

Nuevo objeto Task de continuación.A new continuation Task.

Excepciones

El argumento scheduler es null.The scheduler argument is null.

El argumento continuationOptions especifica un valor no válido para TaskContinuationOptions.The continuationOptions argument specifies an invalid value for TaskContinuationOptions.

Comentarios

El devuelto Task no se programará para su ejecución hasta que se complete la tarea actual.The returned Task will not be scheduled for execution until the current task has completed. Si no se cumplen los criterios continuationOptions especificados a través del parámetro, la tarea de continuación se cancelará en lugar de programar.If the criteria specified through the continuationOptions parameter are not met, the continuation task will be canceled instead of scheduled.

Consulte también:

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

Crea una continuación que se ejecuta según la condición especificada en 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

Parámetros

continuationAction
Action<Task<TResult>>

Una acción para ejecutar según la condición especificada en continuationOptions.An action to run according the condition specified in continuationOptions. Cuando se ejecute, al delegado se le pasará la tarea completada como un argumento.When run, the delegate will be passed the completed task as an argument.

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

CancellationToken que se va a asignar a la nueva tarea de continuación.The CancellationToken that will be assigned to the new continuation task.

continuationOptions
TaskContinuationOptions TaskContinuationOptions TaskContinuationOptions TaskContinuationOptions

Opciones para la programación y el comportamiento de la continuación.Options for when the continuation is scheduled and how it behaves. Incluye criterios, como OnlyOnCanceled, y opciones de ejecución, como ExecuteSynchronously.This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.

scheduler
TaskScheduler TaskScheduler TaskScheduler TaskScheduler

Objeto TaskScheduler que se va a asociar a la tarea de continuación y se va a usar para su ejecución.The TaskScheduler to associate with the continuation task and to use for its execution.

Devoluciones

Nuevo objeto Task de continuación.A new continuation Task.

Excepciones

Se ha eliminado Task<TResult>.The Task<TResult> has been disposed.

O bien-or- El CancellationTokenSource que creó cancellationToken ya se ha eliminado.The CancellationTokenSource that created cancellationToken has already been disposed.

El argumento continuationAction es null.The continuationAction argument is null.

o bien-or- El argumento scheduler es null.The scheduler argument is null.

El argumento continuationOptions especifica un valor no válido para TaskContinuationOptions.The continuationOptions argument specifies an invalid value for TaskContinuationOptions.

Comentarios

El devuelto Task no se programará para su ejecución hasta que se complete la tarea actual.The returned Task will not be scheduled for execution until the current task has completed. Si no se cumplen los criterios continuationOptions especificados a través del parámetro, la tarea de continuación se cancelará en lugar de programar.If the criteria specified through the continuationOptions parameter are not met, the continuation task will be canceled instead of scheduled. Para más información, consulte Chaining Tasks by Using Continuation Tasks (Encadenar tareas mediante tareas de continuación).For more information, see Chaining Tasks by Using Continuation Tasks.

Consulte también:

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

Crea una continuación que se ejecuta cuando se completa el objeto Task<TResult> de destino.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);
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

continuationAction
Action<Task<TResult>,Object>

Acción que se va a ejecutar cuando se complete el objeto Task<TResult>.An action to run when the Task<TResult> completes. Cuando se ejecute, se pasarán al delegado la tarea completada y el objeto de estado proporcionado por el llamador como argumentos.When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.

state
Object Object Object Object

Objeto que representa los datos que la acción de continuación va a usar.An object representing data to be used by the continuation action.

scheduler
TaskScheduler TaskScheduler TaskScheduler TaskScheduler

Objeto TaskScheduler que se va a asociar a la tarea de continuación y se va a usar para su ejecución.The TaskScheduler to associate with the continuation task and to use for its execution.

Devoluciones

Nuevo objeto Task de continuación.A new continuation Task.

Excepciones

El argumento scheduler es null.The scheduler argument is null.

Comentarios

El devuelto Task no se programará para su ejecución hasta que se complete la tarea actual, si se completa debido a que la ejecución se ha completado correctamente, a que se ha producido un error debido a una excepción no controlada o a un cierre temprano debido a su cancelación.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.

Consulte también:

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

Crea una continuación que se ejecuta cuando se completa el objeto Task<TResult> de destino.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);
override this.ContinueWith : Action<System.Threading.Tasks.Task<'Result>, obj> * obj * System.Threading.CancellationToken -> System.Threading.Tasks.Task

Parámetros

continuationAction
Action<Task<TResult>,Object>

Acción que se va a ejecutar cuando se complete el objeto Task<TResult>.An action to run when the Task<TResult> completes. Cuando se ejecute, se pasarán al delegado la tarea completada y el objeto de estado proporcionado por el llamador como argumentos.When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.

state
Object Object Object Object

Objeto que representa los datos que la acción de continuación va a usar.An object representing data to be used by the continuation action.

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

CancellationToken que se va a asignar a la nueva tarea de continuación.The CancellationToken that will be assigned to the new continuation task.

Devoluciones

Nuevo objeto Task de continuación.A new continuation Task.

Excepciones

El argumento continuationAction es null.The continuationAction argument is null.

Comentarios

El devuelto Task no se programará para su ejecución hasta que se complete la tarea actual, si se completa debido a que la ejecución se ha completado correctamente, a que se ha producido un error debido a una excepción no controlada o a un cierre temprano debido a su cancelación.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.

Consulte también:

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

Crea una continuación que se ejecuta cuando se completa el objeto Task<TResult> de destino.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);
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

continuationAction
Action<Task<TResult>,Object>

Acción que se va a ejecutar cuando se complete el objeto Task<TResult>.An action to run when the Task<TResult> completes. Cuando se ejecute, se pasarán al delegado la tarea completada y el objeto de estado proporcionado por el llamador como argumentos.When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.

state
Object Object Object Object

Objeto que representa los datos que la acción de continuación va a usar.An object representing data to be used by the continuation action.

continuationOptions
TaskContinuationOptions TaskContinuationOptions TaskContinuationOptions TaskContinuationOptions

Opciones para la programación y el comportamiento de la continuación.Options for when the continuation is scheduled and how it behaves. Incluye criterios tales como OnlyOnCanceled, así como opciones de ejecución tales como ExecuteSynchronously.This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.

Devoluciones

Nuevo objeto Task de continuación.A new continuation Task.

Excepciones

El argumento continuationAction es null.The continuationAction argument is null.

El argumento continuationOptions especifica un valor no válido para TaskContinuationOptions.The continuationOptions argument specifies an invalid value for TaskContinuationOptions.

Comentarios

El devuelto Task no se programará para su ejecución hasta que se complete la tarea actual.The returned Task will not be scheduled for execution until the current task has completed. Si no se cumplen los criterios de continuationOptions continuación especificados a través del parámetro, la tarea de continuación se cancelará en lugar de programada.If the continuation criteria specified through the continuationOptions parameter are not met, the continuation task will be canceled instead of scheduled.

Consulte también:

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

Crea una continuación que se ejecuta según la condición especificada en 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

continuationAction
Action<Task<TResult>>

Una acción según la condición especificada en continuationOptions.An action to according the condition specified in continuationOptions. Cuando se ejecute, al delegado se le pasará la tarea completada como un argumento.When run, the delegate will be passed the completed task as an argument.

continuationOptions
TaskContinuationOptions TaskContinuationOptions TaskContinuationOptions TaskContinuationOptions

Opciones para la programación y el comportamiento de la continuación.Options for when the continuation is scheduled and how it behaves. Incluye criterios, como OnlyOnCanceled, y opciones de ejecución, como ExecuteSynchronously.This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.

Devoluciones

Nuevo objeto Task de continuación.A new continuation Task.

Excepciones

El argumento continuationAction es null.The continuationAction argument is null.

El argumento continuationOptions especifica un valor no válido para TaskContinuationOptions.The continuationOptions argument specifies an invalid value for TaskContinuationOptions.

Comentarios

El devuelto Task no se programará para su ejecución hasta que se complete la tarea actual.The returned Task will not be scheduled for execution until the current task has completed. Si no se cumplen los criterios de continuationOptions continuación especificados a través del parámetro, la tarea de continuación se cancelará en lugar de programada.If the continuation criteria specified through the continuationOptions parameter are not met, the continuation task will be canceled instead of scheduled.

Para más información, consulte Chaining Tasks by Using Continuation Tasks (Encadenar tareas mediante tareas de continuación).For more information, see Chaining Tasks by Using Continuation Tasks.

Consulte también:

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

Crea una continuación que se puede cancelar y se ejecuta de forma asincrónica al completarse el parámetro Task<TResult> de destino.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

Parámetros

continuationAction
Action<Task<TResult>>

Acción que se va a ejecutar cuando se complete el objeto Task<TResult>.An action to run when the Task<TResult> completes. Cuando se ejecuta, se pasa la tarea completada al delegado como argumento.When run, the delegate is passed the completed task as an argument.

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

Token de cancelación que se pasa a la nueva tarea de continuación.The cancellation token that is passed to the new continuation task.

Devoluciones

Una tarea de continuación nueva.A new continuation task.

Excepciones

Se ha eliminado Task<TResult>.The Task<TResult> has been disposed.

O bien-or- Se ha eliminado el CancellationTokenSource que ha creado cancellationToken.The CancellationTokenSource that created cancellationToken has been disposed.

El argumento continuationAction es null.The continuationAction argument is null.

Ejemplos

En el ejemplo siguiente se crea una tarea antecedente que usa el criba de Eratóstenes para calcular los números primos entre 1 y un valor especificado por el usuario.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. Una matriz se utiliza para almacenar información sobre los números primos.An array is used to hold information about the prime numbers. El índice de la matriz representa el número y el valor del elemento indica si ese número es compuesto (su valor truees) o primo (su valor falsees).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). Esta tarea se pasa a continuación a una tarea de continuación, que es responsable de extraer los números primos de la matriz de enteros y mostrarlos.This task is then passed to a continuation task, which is responsible for extracting the prime numbers from the integer array and displaying them.

Se pasa un token de cancelación a las tareas antecedente y continuación.A cancellation token is passed to both the antecedent and the continuation task. Un System.Timers.Timer objeto se utiliza para definir un valor de tiempo de espera de 100 milisegundos.A System.Timers.Timer object is used to define a timeout value of 100 milliseconds. Si el evento se activa, CancellationTokenSource.Cancel se llama al método y se usa el token de cancelación para solicitar la cancelación de las tareas.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, si se proporciona un valor de aproximadamente 100.000, el intervalo de tiempo de espera Timer.Elapsed expira y se activa el evento, y se establece la solicitud de cancelación.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.

Comentarios

El devuelto Task no se programará para su ejecución hasta que se complete la tarea actual, si se completa debido a que la ejecución se ha completado correctamente, a que se ha producido un error debido a una excepción no controlada o a un cierre temprano debido a su cancelación.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.

Consulte también:

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

Crea una continuación a la que se pasa información de estado y que se ejecuta cuando el objeto Task<TResult> de destino se completa.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);
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

continuationAction
Action<Task<TResult>,Object>

Acción que se va a ejecutar cuando se complete el objeto Task<TResult>.An action to run when the Task<TResult> completes. Cuando se ejecuta, se pasan al delegado la tarea completada y el objeto de estado proporcionado por el autor de la llamada como argumentos.When run, the delegate is passed the completed task and the caller-supplied state object as arguments.

state
Object Object Object Object

Objeto que representa los datos que la acción de continuación va a usar.An object representing data to be used by the continuation action.

Devoluciones

Nuevo objeto Task de continuación.A new continuation Task.

Excepciones

El argumento continuationAction es null.The continuationAction argument is null.

Ejemplos

En el ejemplo siguiente se crea una tarea que se pasa un entero entre 2 y 20 y devuelve una matriz que contiene los diez primeros exponentes (de n1 a n10) de ese 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. Una tarea de continuación es responsable de mostrar los exponentes.A continuation task is then responsible for displaying the exponents. Se pasa el antecedente y el número original cuyos exponentes genera el antecedente.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

Comentarios

El devuelto Task no se programará para su ejecución hasta que se complete la tarea actual, si se completa debido a que la ejecución se ha completado correctamente, a que se ha producido un error debido a una excepción no controlada o a un cierre temprano debido a su cancelación.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.

Consulte también:

ContinueWith(Action<Task<TResult>>) ContinueWith(Action<Task<TResult>>) ContinueWith(Action<Task<TResult>>) ContinueWith(Action<Task<TResult>>)

Crea una continuación que se ejecuta de manera asincrónica cuando se completa la tarea de destino.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

continuationAction
Action<Task<TResult>>

Una acción que se ejecuta cuando se completa el Task<TResult> antecedente.An action to run when the antecedent Task<TResult> completes. Cuando se ejecute, al delegado se le pasará la tarea completada como un argumento.When run, the delegate will be passed the completed task as an argument.

Devoluciones

Una tarea de continuación nueva.A new continuation task.

Excepciones

El argumento continuationAction es null.The continuationAction argument is null.

Ejemplos

En el ejemplo siguiente se crea una tarea antecedente que usa el criba de Eratóstenes para calcular los números primos entre 1 y un valor especificado por el usuario.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. Una matriz se utiliza para almacenar información sobre los números primos.An array is used to hold information about the prime numbers. El índice de la matriz representa el número y el valor del elemento indica si ese número es compuesto (su valor truees) o primo (su valor falsees).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). Esta tarea se pasa a continuación a una tarea de continuación, que es responsable de extraer los números primos de la matriz de enteros y mostrarlos.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.

Comentarios

El devuelto Task no se programará para su ejecución hasta que se complete la tarea actual, si se completa debido a que la ejecución se ha completado correctamente, a que se ha producido un error debido a una excepción no controlada o a un cierre temprano debido a su cancelación.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.

Consulte también:

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

Crea una continuación que se ejecuta de manera asincrónica cuando se completa el objeto Task<TResult> de destino.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

continuationAction
Action<Task<TResult>>

Acción que se va a ejecutar cuando se complete el objeto Task<TResult>.An action to run when the Task<TResult> completes. Cuando se ejecute, al delegado se le pasará la tarea completada como un argumento.When run, the delegate will be passed the completed task as an argument.

scheduler
TaskScheduler TaskScheduler TaskScheduler TaskScheduler

Objeto TaskScheduler que se va a asociar a la tarea de continuación y se va a usar para su ejecución.The TaskScheduler to associate with the continuation task and to use for its execution.

Devoluciones

Nuevo objeto Task de continuación.A new continuation Task.

Excepciones

El argumento continuationAction es null.The continuationAction argument is null.

O bien-or- El argumento scheduler es null.The scheduler argument is null.

Comentarios

El devuelto Task no se programará para su ejecución hasta que se complete la tarea actual, si se completa debido a que la ejecución se ha completado correctamente, a que se ha producido un error debido a una excepción no controlada o a un cierre temprano debido a su cancelación.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.

Consulte también:

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

Crea una continuación que se ejecuta cuando se completa el objeto Task<TResult> de destino.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);
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>

Parámetros de tipo

TNewResult

Tipo de resultado generado por la continuación.The type of the result produced by the continuation.

Parámetros

continuationFunction
Func<Task<TResult>,Object,TNewResult>

Función que se va a ejecutar cuando se complete el objeto Task<TResult>.A function to run when the Task<TResult> completes. Cuando se ejecute, se pasarán al delegado la tarea completada y el objeto de estado proporcionado por el llamador como argumentos.When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.

state
Object Object Object Object

Objeto que representa los datos que la función de continuación va a usar.An object representing data to be used by the continuation function.

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

CancellationToken que se va a asignar a la nueva tarea.The CancellationToken that will be assigned to the new task.

continuationOptions
TaskContinuationOptions TaskContinuationOptions TaskContinuationOptions TaskContinuationOptions

Opciones para la programación y el comportamiento de la continuación.Options for when the continuation is scheduled and how it behaves. Incluye criterios, como OnlyOnCanceled, y opciones de ejecución, como ExecuteSynchronously.This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.

scheduler
TaskScheduler TaskScheduler TaskScheduler TaskScheduler

Objeto TaskScheduler que se va a asociar a la tarea de continuación y se va a usar para su ejecución.The TaskScheduler to associate with the continuation task and to use for its execution.

Devoluciones

Task<TNewResult>

Nuevo objeto Task<TResult> de continuación.A new continuation Task<TResult>.

Excepciones

El argumento scheduler es null.The scheduler argument is null.

El argumento continuationOptions especifica un valor no válido para TaskContinuationOptions.The continuationOptions argument specifies an invalid value for TaskContinuationOptions.

Comentarios

El devuelto Task<TResult> no se programará para su ejecución hasta que se complete la tarea actual, si se completa debido a que la ejecución se ha completado correctamente, a que se ha producido un error debido a una excepción no controlada o a un cierre temprano debido a su cancelación.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.

Cuando se ejecuta, debe Task<TResult>devolver. continuationFunctionThe continuationFunction, when executed, should return a Task<TResult>. El estado de finalización de esta tarea se transferirá a la tarea Task<TResult>.ContinueWith devuelta por la llamada.This task's completion state will be transferred to the task returned from the Task<TResult>.ContinueWith call.

Consulte también:

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

Crea una continuación que se ejecuta según la condición especificada en 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>

Parámetros de tipo

TNewResult

Tipo de resultado generado por la continuación.The type of the result produced by the continuation.

Parámetros

continuationFunction
Func<Task<TResult>,TNewResult>

Una función para ejecutar según la condición especificada en continuationOptions.A function to run according the condition specified in continuationOptions.

Cuando se ejecute, al delegado se le pasará la tarea completada como un argumento.When run, the delegate will be passed as an argument this completed task.

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

CancellationToken que se va a asignar a la nueva tarea.The CancellationToken that will be assigned to the new task.

continuationOptions
TaskContinuationOptions TaskContinuationOptions TaskContinuationOptions TaskContinuationOptions

Opciones para la programación y el comportamiento de la continuación.Options for when the continuation is scheduled and how it behaves. Incluye criterios, como OnlyOnCanceled, y opciones de ejecución, como ExecuteSynchronously.This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.

scheduler
TaskScheduler TaskScheduler TaskScheduler TaskScheduler

Objeto TaskScheduler que se va a asociar a la tarea de continuación y se va a usar para su ejecución.The TaskScheduler to associate with the continuation task and to use for its execution.

Devoluciones

Task<TNewResult>

Nuevo objeto Task<TResult> de continuación.A new continuation Task<TResult>.

Excepciones

Se ha eliminado Task<TResult>.The Task<TResult> has been disposed.

o bien-or- El CancellationTokenSource que creó cancellationToken ya se ha eliminado.The CancellationTokenSource that created cancellationToken has already been disposed.

El argumento continuationFunction es null.The continuationFunction argument is null.

o bien-or- El argumento scheduler es null.The scheduler argument is null.

El argumento continuationOptions especifica un valor no válido para TaskContinuationOptions.The continuationOptions argument specifies an invalid value for TaskContinuationOptions.

Comentarios

El devuelto Task<TResult> no se programará para su ejecución hasta que se complete la tarea actual, si se completa debido a que la ejecución se ha completado correctamente, a que se ha producido un error debido a una excepción no controlada o a un cierre temprano debido a su cancelación.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.

Cuando se ejecuta, debe Task<TResult>devolver. continuationFunctionThe continuationFunction, when executed, should return a Task<TResult>.

Consulte también:

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

Crea una continuación que se ejecuta cuando se completa el objeto Task<TResult> de destino.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);
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

Tipo de resultado generado por la continuación.The type of the result produced by the continuation.

Parámetros

continuationFunction
Func<Task<TResult>,Object,TNewResult>

Función que se va a ejecutar cuando se complete el objeto Task<TResult>.A function to run when the Task<TResult> completes. Cuando se ejecute, se pasarán al delegado la tarea completada y el objeto de estado proporcionado por el llamador como argumentos.When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.

state
Object Object Object Object

Objeto que representa los datos que la función de continuación va a usar.An object representing data to be used by the continuation function.

scheduler
TaskScheduler TaskScheduler TaskScheduler TaskScheduler

Objeto TaskScheduler que se va a asociar a la tarea de continuación y se va a usar para su ejecución.The TaskScheduler to associate with the continuation task and to use for its execution.

Devoluciones

Task<TNewResult>

Nuevo objeto Task<TResult> de continuación.A new continuation Task<TResult>.

Excepciones

El argumento scheduler es null.The scheduler argument is null.

Comentarios

El devuelto Task<TResult> no se programará para su ejecución hasta que se complete la tarea actual, si se completa debido a que la ejecución se ha completado correctamente, a que se ha producido un error debido a una excepción no controlada o a un cierre temprano debido a su cancelación.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.

Consulte también:

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

Crea una continuación que se ejecuta cuando se completa el objeto Task<TResult> de destino.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);
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

Tipo de resultado generado por la continuación.The type of the result produced by the continuation.

Parámetros

continuationFunction
Func<Task<TResult>,Object,TNewResult>

Función que se va a ejecutar cuando se complete el objeto Task<TResult>.A function to run when the Task<TResult> completes. Cuando se ejecute, se pasarán al delegado la tarea completada y el objeto de estado proporcionado por el llamador como argumentos.When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.

state
Object Object Object Object

Objeto que representa los datos que la función de continuación va a usar.An object representing data to be used by the continuation function.

continuationOptions
TaskContinuationOptions TaskContinuationOptions TaskContinuationOptions TaskContinuationOptions

Opciones para la programación y el comportamiento de la continuación.Options for when the continuation is scheduled and how it behaves. Incluye criterios, como OnlyOnCanceled, y opciones de ejecución, como ExecuteSynchronously.This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.

Devoluciones

Task<TNewResult>

Nuevo objeto Task<TResult> de continuación.A new continuation Task<TResult>.

Excepciones

El argumento continuationFunction es null.The continuationFunction argument is null.

El argumento continuationOptions especifica un valor no válido para TaskContinuationOptions.The continuationOptions argument specifies an invalid value for TaskContinuationOptions.

Comentarios

El devuelto Task<TResult> no se programará para su ejecución hasta que se complete la tarea actual, si se completa debido a que la ejecución se ha completado correctamente, a que se ha producido un error debido a una excepción no controlada o a un cierre temprano debido a su cancelación.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.

Cuando se ejecuta, debe Task<TResult>devolver. continuationFunctionThe continuationFunction, when executed, should return a Task<TResult>. El estado de finalización de esta tarea se transferirá a la tarea devuelta por la llamada a ContinueWith.This task's completion state will be transferred to the task returned from the ContinueWith call.

Consulte también:

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

Crea una continuación que se ejecuta cuando se completa el objeto Task<TResult> de destino.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);
override this.ContinueWith : Func<System.Threading.Tasks.Task<'Result>, obj, 'NewResult> * obj * System.Threading.CancellationToken -> System.Threading.Tasks.Task<'NewResult>

Parámetros de tipo

TNewResult

Tipo de resultado generado por la continuación.The type of the result produced by the continuation.

Parámetros

continuationFunction
Func<Task<TResult>,Object,TNewResult>

Función que se va a ejecutar cuando se complete el objeto Task<TResult>.A function to run when the Task<TResult> completes. Cuando se ejecute, se pasarán al delegado la tarea completada y el objeto de estado proporcionado por el llamador como argumentos.When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.

state
Object Object Object Object

Objeto que representa los datos que la función de continuación va a usar.An object representing data to be used by the continuation function.

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

CancellationToken que se va a asignar a la nueva tarea.The CancellationToken that will be assigned to the new task.

Devoluciones

Task<TNewResult>

Nuevo objeto Task<TResult> de continuación.A new continuation Task<TResult>.

Excepciones

El argumento continuationFunction es null.The continuationFunction argument is null.

Comentarios

El devuelto Task<TResult> no se programará para su ejecución hasta que se complete la tarea actual, si se completa debido a que la ejecución se ha completado correctamente, a que se ha producido un error debido a una excepción no controlada o a un cierre temprano debido a su cancelación.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.

Consulte también:

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

Crea una continuación que se ejecuta según la condición especificada en 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

Tipo de resultado generado por la continuación.The type of the result produced by the continuation.

Parámetros

continuationFunction
Func<Task<TResult>,TNewResult>

Una función para ejecutar según la condición especificada en continuationOptions.A function to run according the condition specified in continuationOptions.

Cuando se ejecute, al delegado se le pasará la tarea completada como un argumento.When run, the delegate will be passed the completed task as an argument.

continuationOptions
TaskContinuationOptions TaskContinuationOptions TaskContinuationOptions TaskContinuationOptions

Opciones para la programación y el comportamiento de la continuación.Options for when the continuation is scheduled and how it behaves. Incluye criterios, como OnlyOnCanceled, y opciones de ejecución, como ExecuteSynchronously.This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.

Devoluciones

Task<TNewResult>

Nuevo objeto Task<TResult> de continuación.A new continuation Task<TResult>.

Excepciones

El argumento continuationFunction es null.The continuationFunction argument is null.

El argumento continuationOptions especifica un valor no válido para TaskContinuationOptions.The continuationOptions argument specifies an invalid value for TaskContinuationOptions.

Comentarios

El devuelto Task<TResult> no se programará para su ejecución hasta que se complete la tarea actual, si se completa debido a que la ejecución se ha completado correctamente, a que se ha producido un error debido a una excepción no controlada o a un cierre temprano debido a su cancelación.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.

Cuando se ejecuta, debe Task<TResult>devolver. continuationFunctionThe continuationFunction, when executed, should return a Task<TResult>.

Consulte también:

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

Crea una continuación que se ejecuta de manera asincrónica cuando se completa el objeto Task<TResult> de destino.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>

Parámetros de tipo

TNewResult

Tipo de resultado generado por la continuación.The type of the result produced by the continuation.

Parámetros

continuationFunction
Func<Task<TResult>,TNewResult>

Función que se va a ejecutar cuando se complete el objeto Task<TResult>.A function to run when the Task<TResult> completes. Cuando se ejecute, al delegado se le pasará la tarea completada como un argumento.When run, the delegate will be passed the completed task as an argument.

cancellationToken
CancellationToken CancellationToken CancellationToken CancellationToken

CancellationToken que se va a asignar a la nueva tarea.The CancellationToken that will be assigned to the new task.

Devoluciones

Task<TNewResult>

Nuevo objeto Task<TResult> de continuación.A new continuation Task<TResult>.

Excepciones

Se ha eliminado Task<TResult>.The Task<TResult> has been disposed.

O bien-or- El CancellationTokenSource que creó cancellationToken ya se ha eliminado.The CancellationTokenSource that created cancellationToken has already been disposed.

El argumento continuationFunction es null.The continuationFunction argument is null.

Comentarios

El devuelto Task<TResult> no se programará para su ejecución hasta que se complete la tarea actual, si se completa debido a que la ejecución se ha completado correctamente, a que se ha producido un error debido a una excepción no controlada o a un cierre temprano debido a su cancelación.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.

Consulte también:

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

Crea una continuación que se ejecuta cuando se completa el objeto Task<TResult> de destino.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);
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

Tipo de resultado generado por la continuación.The type of the result produced by the continuation.

Parámetros

continuationFunction
Func<Task<TResult>,Object,TNewResult>

Función que se va a ejecutar cuando se complete el objeto Task<TResult>.A function to run when the Task<TResult> completes. Cuando se ejecute, se pasarán al delegado la tarea completada y el objeto de estado proporcionado por el llamador como argumentos.When run, the delegate will be passed the completed task and the caller-supplied state object as arguments.

state
Object Object Object Object

Objeto que representa los datos que la función de continuación va a usar.An object representing data to be used by the continuation function.

Devoluciones

Task<TNewResult>

Nuevo objeto Task<TResult> de continuación.A new continuation Task<TResult>.

Excepciones

El argumento continuationFunction es null.The continuationFunction argument is null.

Ejemplos

En el ejemplo siguiente se crea una cadena de tareas de continuación.The following example creates a chain of continuation tasks. Cada tarea proporciona la hora actual, un DateTime objeto, para el argumento ContinueWith(Action<Task,Object>, Object) de estado del 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 la hora a la que se crea la tarea de continuación.Each DateTime value represents the time at which the continue task is created. Cada tarea genera como resultado un segundo DateTime valor que representa la hora en que finaliza la tarea.Each task produces as its result a second DateTime value that represents the time at which the task finishes. Una vez finalizadas todas las tareas, en el ejemplo se muestra la fecha y la hora en que se inicia y finaliza cada tarea de continuación.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.

Comentarios

El devuelto Task<TResult> no se programará para su ejecución hasta que se complete la tarea actual, si se completa debido a que la ejecución se ha completado correctamente, a que se ha producido un error debido a una excepción no controlada o a un cierre temprano debido a su cancelación.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.

Consulte también:

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

Crea una continuación que se ejecuta de manera asincrónica cuando se completa el objeto Task<TResult> de destino.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

Tipo de resultado generado por la continuación.The type of the result produced by the continuation.

Parámetros

continuationFunction
Func<Task<TResult>,TNewResult>

Función que se va a ejecutar cuando se complete el objeto Task<TResult>.A function to run when the Task<TResult> completes. Cuando se ejecute, al delegado se le pasará la tarea completada como un argumento.When run, the delegate will be passed the completed task as an argument.

Devoluciones

Task<TNewResult>

Nuevo objeto Task<TResult> de continuación.A new continuation Task<TResult>.

Excepciones

El argumento continuationFunction es null.The continuationFunction argument is null.

Comentarios

El devuelto Task<TResult> no se programará para su ejecución hasta que se complete la tarea actual, si se completa debido a que la ejecución se ha completado correctamente, a que se ha producido un error debido a una excepción no controlada o a un cierre temprano debido a su cancelación.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.

Consulte también:

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

Crea una continuación que se ejecuta de manera asincrónica cuando se completa el objeto Task<TResult> de destino.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

Tipo de resultado generado por la continuación.The type of the result produced by the continuation.

Parámetros

continuationFunction
Func<Task<TResult>,TNewResult>

Función que se va a ejecutar cuando se complete el objeto Task<TResult>.A function to run when the Task<TResult> completes. Cuando se ejecute, al delegado se le pasará la tarea completada como un argumento.When run, the delegate will be passed the completed task as an argument.

scheduler
TaskScheduler TaskScheduler TaskScheduler TaskScheduler

Objeto TaskScheduler que se va a asociar a la tarea de continuación y se va a usar para su ejecución.The TaskScheduler to associate with the continuation task and to use for its execution.

Devoluciones

Task<TNewResult>

Nuevo objeto Task<TResult> de continuación.A new continuation Task<TResult>.

Excepciones

El argumento continuationFunction es null.The continuationFunction argument is null.

O bien-or- El argumento scheduler es null.The scheduler argument is null.

Comentarios

El devuelto Task<TResult> no se programará para su ejecución hasta que se complete la tarea actual, si se completa debido a que la ejecución se ha completado correctamente, a que se ha producido un error debido a una excepción no controlada o a un cierre temprano debido a su cancelación.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.

Consulte también:

Se aplica a