Task<TResult>.ContinueWith Método
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Crea una tarea de continuación que se ejecuta cuando se completa otra tarea.
Sobrecargas
ContinueWith(Action<Task<TResult>,Object>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler)
Crea una continuación que se ejecuta cuando se completa el destino Task<TResult> .
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
Public Function ContinueWith (continuationAction As Action(Of Task(Of TResult), Object), state As Object, cancellationToken As CancellationToken, continuationOptions As TaskContinuationOptions, scheduler As TaskScheduler) As Task
Parámetros
Acción que se va a ejecutar cuando Task<TResult> se completa. Cuando se ejecuta, el delegado se pasará la tarea completada y el objeto de estado proporcionado por el autor de la llamada como argumentos.
- state
- Object
Objeto que representa los datos que va a usar la acción de continuación.
- cancellationToken
- CancellationToken
que CancellationToken se asignará a la nueva tarea de continuación.
- continuationOptions
- TaskContinuationOptions
Opciones para cuándo se programa la continuación y cómo se comporta. Esto incluye criterios, como OnlyOnCanceled, así como opciones de ejecución, como ExecuteSynchronously.
- scheduler
- TaskScheduler
TaskScheduler que se va a asociar a la tarea de continuación y que se va a usar para su ejecución.
Devoluciones
Nueva continuación Task.
Excepciones
El scheduler argumento es null.
El continuationOptions argumento especifica un valor no válido para TaskContinuationOptions.
El elemento proporcionado CancellationToken ya se ha eliminado.
Comentarios
El devuelto Task no se programará para su ejecución hasta que se haya completado la tarea actual. Si no se cumplen los criterios especificados a través del continuationOptions parámetro , la tarea de continuación se cancelará en lugar de programada.
Consulte también
Se aplica a
ContinueWith(Action<Task<TResult>>, CancellationToken, TaskContinuationOptions, TaskScheduler)
Crea una continuación que se ejecuta según la condición especificada en continuationOptions.
public:
System::Threading::Tasks::Task ^ ContinueWith(Action<System::Threading::Tasks::Task<TResult> ^> ^ continuationAction, System::Threading::CancellationToken cancellationToken, System::Threading::Tasks::TaskContinuationOptions continuationOptions, System::Threading::Tasks::TaskScheduler ^ scheduler);
public System.Threading.Tasks.Task ContinueWith(Action<System.Threading.Tasks.Task<TResult>> continuationAction, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskContinuationOptions continuationOptions, System.Threading.Tasks.TaskScheduler scheduler);
override this.ContinueWith : Action<System.Threading.Tasks.Task<'Result>> * System.Threading.CancellationToken * System.Threading.Tasks.TaskContinuationOptions * System.Threading.Tasks.TaskScheduler -> System.Threading.Tasks.Task
Public Function ContinueWith (continuationAction As Action(Of Task(Of TResult)), cancellationToken As CancellationToken, continuationOptions As TaskContinuationOptions, scheduler As TaskScheduler) As Task
Parámetros
Una acción para ejecutarse según la condición especificada en continuationOptions. Cuando se ejecute, el delegado se pasará la tarea completada como argumento.
- cancellationToken
- CancellationToken
que CancellationToken se asignará a la nueva tarea de continuación.
- continuationOptions
- TaskContinuationOptions
Opciones para cuándo se programa la continuación y cómo se comporta. Esto incluye criterios, como OnlyOnCanceled, así como opciones de ejecución, como ExecuteSynchronously.
- scheduler
- TaskScheduler
TaskScheduler que se va a asociar a la tarea de continuación y que se va a usar para su ejecución.
Devoluciones
Nueva continuación Task.
Excepciones
Se Task<TResult> ha eliminado .
O bien
El CancellationTokenSource objeto que creó cancellationToken ya se ha eliminado.
El continuationAction argumento es null.
O bien
El scheduler argumento es null.
El continuationOptions argumento especifica un valor no válido para TaskContinuationOptions.
Comentarios
El devuelto Task no se programará para su ejecución hasta que se haya completado la tarea actual. Si no se cumplen los criterios especificados a través del continuationOptions parámetro , la tarea de continuación se cancelará en lugar de programada. Para más información, consulte Encadenar tareas mediante tareas de continuación.
Consulte también
- Biblioteca paralela de tareas (TPL)
- Programación asincrónica basada en tareas
- Encadenado de tareas mediante tareas de continuación
Se aplica a
ContinueWith(Action<Task<TResult>,Object>, Object, TaskScheduler)
Crea una continuación que se ejecuta cuando se completa el destino Task<TResult> .
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
Acción que se va a ejecutar cuando Task<TResult> se completa. Cuando se ejecuta, el delegado se pasará la tarea completada y el objeto de estado proporcionado por el autor de la llamada como argumentos.
- state
- Object
Objeto que representa los datos que va a usar la acción de continuación.
- scheduler
- TaskScheduler
TaskScheduler que se va a asociar a la tarea de continuación y que se va a usar para su ejecución.
Devoluciones
Nueva continuación Task.
Excepciones
El scheduler argumento es null.
Comentarios
El devuelto Task no se programará para su ejecución hasta que se haya completado la tarea actual, independientemente de si se completa debido a la ejecución correcta, a errores debido a una excepción no controlada o a la salida anticipada debido a la cancelación.
Consulte también
Se aplica a
ContinueWith(Action<Task<TResult>,Object>, Object, CancellationToken)
Crea una continuación que se ejecuta cuando se completa el destino Task<TResult> .
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
Public Function ContinueWith (continuationAction As Action(Of Task(Of TResult), Object), state As Object, cancellationToken As CancellationToken) As Task
Parámetros
Acción que se va a ejecutar cuando Task<TResult> se completa. Cuando se ejecuta, el delegado se pasará la tarea completada y el objeto de estado proporcionado por el autor de la llamada como argumentos.
- state
- Object
Objeto que representa los datos que va a usar la acción de continuación.
- cancellationToken
- CancellationToken
que CancellationToken se asignará a la nueva tarea de continuación.
Devoluciones
Nueva continuación Task.
Excepciones
El continuationAction argumento es null.
El elemento proporcionado CancellationToken ya se ha eliminado.
Comentarios
El devuelto Task no se programará para su ejecución hasta que se haya completado la tarea actual, independientemente de si se completa debido a la ejecución correcta, a errores debido a una excepción no controlada o a la salida anticipada debido a la cancelación.
Consulte también
Se aplica a
ContinueWith(Action<Task<TResult>,Object>, Object, TaskContinuationOptions)
Crea una continuación que se ejecuta cuando se completa el destino Task<TResult> .
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
Acción que se va a ejecutar cuando Task<TResult> se completa. Cuando se ejecuta, el delegado se pasará la tarea completada y el objeto de estado proporcionado por el autor de la llamada como argumentos.
- state
- Object
Objeto que representa los datos que va a usar la acción de continuación.
- continuationOptions
- TaskContinuationOptions
Opciones para cuándo se programa la continuación y cómo se comporta. Esto incluye criterios, como OnlyOnCanceled, así como opciones de ejecución, como ExecuteSynchronously.
Devoluciones
Nueva continuación Task.
Excepciones
El continuationAction argumento es null.
El continuationOptions argumento especifica un valor no válido para TaskContinuationOptions.
Comentarios
El devuelto Task no se programará para su ejecución hasta que se haya completado la tarea actual. Si no se cumplen los criterios de continuación especificados a través del continuationOptions parámetro , la tarea de continuación se cancelará en lugar de programada.
Consulte también
Se aplica a
ContinueWith(Action<Task<TResult>>, TaskContinuationOptions)
Crea una continuación que se ejecuta según la condición especificada en 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
Una acción a según la condición especificada en continuationOptions. Cuando se ejecute, el delegado se pasará la tarea completada como argumento.
- continuationOptions
- TaskContinuationOptions
Opciones para cuándo se programa la continuación y cómo se comporta. Esto incluye criterios, como OnlyOnCanceled, así como opciones de ejecución, como ExecuteSynchronously.
Devoluciones
Nueva continuación Task.
Excepciones
Se Task<TResult> ha eliminado .
El continuationAction argumento es null.
El continuationOptions argumento especifica un valor no válido para TaskContinuationOptions.
Comentarios
El devuelto Task no se programará para su ejecución hasta que se haya completado la tarea actual. Si no se cumplen los criterios de continuación especificados a través del continuationOptions parámetro , la tarea de continuación se cancelará en lugar de programada.
Para más información, consulte Encadenar tareas mediante tareas de continuación.
Consulte también
- Biblioteca paralela de tareas (TPL)
- Programación asincrónica basada en tareas
- Encadenado de tareas mediante tareas de continuación
Se aplica a
ContinueWith(Action<Task<TResult>>, CancellationToken)
Crea una continuación cancelable que se ejecuta de forma asincrónica cuando se completa el destino Task<TResult> .
public:
System::Threading::Tasks::Task ^ ContinueWith(Action<System::Threading::Tasks::Task<TResult> ^> ^ continuationAction, System::Threading::CancellationToken cancellationToken);
public System.Threading.Tasks.Task ContinueWith(Action<System.Threading.Tasks.Task<TResult>> continuationAction, System.Threading.CancellationToken cancellationToken);
override this.ContinueWith : Action<System.Threading.Tasks.Task<'Result>> * System.Threading.CancellationToken -> System.Threading.Tasks.Task
Public Function ContinueWith (continuationAction As Action(Of Task(Of TResult)), cancellationToken As CancellationToken) As Task
Parámetros
Acción que se va a ejecutar cuando Task<TResult> se completa. Cuando se ejecuta, el delegado pasa la tarea completada como argumento.
- cancellationToken
- CancellationToken
Token de cancelación que se pasa a la nueva tarea de continuación.
Devoluciones
Una nueva tarea de continuación.
Excepciones
Se Task<TResult> ha eliminado .
O bien
Que CancellationTokenSource se ha creado cancellationToken se ha eliminado.
El continuationAction argumento es null.
Ejemplos
En el ejemplo siguiente se crea una tarea antecedente que usa el Sieve de Eratosthenes para calcular los números primos entre 1 y un valor especificado por el usuario. Una matriz se usa para contener información sobre los números primos. El índice de matriz representa el número y el valor del elemento indica si ese número está compuesto (su valor es true) o primo (su valor es false). A continuación, esta tarea se pasa a una tarea de continuación, que es responsable de extraer los números primos de la matriz de enteros y mostrarlos.
Un token de cancelación se pasa tanto al antecedente como a la tarea de continuación. Un System.Timers.Timer objeto se usa para definir un valor de tiempo de espera de 100 milisegundos. Si se desencadena el evento, se llama al CancellationTokenSource.Cancel método y el token de cancelación se usa para solicitar la cancelación de las tareas.
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] ) {
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] )
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, proporcionar un valor de aproximadamente 100 000 hace que el intervalo de tiempo de espera expire y el Timer.Elapsed evento se active y se establezca la solicitud de cancelación.
Comentarios
El devuelto Task no se programará para su ejecución hasta que se haya completado la tarea actual, independientemente de si se completa debido a la ejecución correcta, a errores debido a una excepción no controlada o a la salida anticipada debido a la cancelación.
Consulte también
- Biblioteca paralela de tareas (TPL)
- Programación asincrónica basada en tareas
- Encadenado de tareas mediante tareas de continuación
Se aplica a
ContinueWith(Action<Task<TResult>,Object>, Object)
Crea una continuación que se pasa información de estado y que se ejecuta cuando se completa el destino Task<TResult> .
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
Acción que se va a ejecutar cuando Task<TResult> se completa. Cuando se ejecuta, el delegado se pasa la tarea completada y el objeto de estado proporcionado por el autor de la llamada como argumentos.
- state
- Object
Objeto que representa los datos que va a usar la acción de continuación.
Devoluciones
Nueva continuación Task.
Excepciones
El continuationAction argumento es null.
Ejemplos
En el ejemplo siguiente se crea una tarea que se pasa un entero entre 2 y 20 y se devuelve una matriz que contiene los diez primeros exponentes (de n1 an 10) de ese número. Una tarea de continuación es responsable de mostrar los exponentes. Se pasa tanto el antecedente como el número original cuyos exponentes genera el antecedente.
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 haya completado la tarea actual, independientemente de si se completa debido a la ejecución correcta, a errores debido a una excepción no controlada o a la salida anticipada debido a la cancelación.
Consulte también
Se aplica a
ContinueWith(Action<Task<TResult>>)
Crea una continuación que se ejecuta de forma asincrónica cuando se completa la tarea de destino.
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
Acción que se va a ejecutar cuando se completa el antecedente Task<TResult> . Cuando se ejecute, el delegado se pasará la tarea completada como argumento.
Devoluciones
Una nueva tarea de continuación.
Excepciones
Se Task<TResult> ha eliminado .
El continuationAction argumento es null.
Ejemplos
En el ejemplo siguiente se crea una tarea antecedente que usa el Sieve de Eratosthenes para calcular los números primos entre 1 y un valor especificado por el usuario. Una matriz se usa para contener información sobre los números primos. El índice de matriz representa el número y el valor del elemento indica si ese número está compuesto (su valor es true) o primo (su valor es false). A continuación, esta tarea se pasa a una tarea de continuación, que es responsable de extraer los números primos de la matriz de enteros y mostrarlos.
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]) {
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])
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 haya completado la tarea actual, independientemente de si se completa debido a la ejecución correcta, a errores debido a una excepción no controlada o a la salida anticipada debido a la cancelación.
Consulte también
- Biblioteca paralela de tareas (TPL)
- Programación asincrónica basada en tareas
- Encadenado de tareas mediante tareas de continuación
Se aplica a
ContinueWith(Action<Task<TResult>>, TaskScheduler)
Crea una continuación que se ejecuta de forma asincrónica cuando se completa el destino Task<TResult> .
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
Acción que se va a ejecutar cuando Task<TResult> se completa. Cuando se ejecute, el delegado se pasará la tarea completada como argumento.
- scheduler
- TaskScheduler
TaskScheduler que se va a asociar a la tarea de continuación y que se va a usar para su ejecución.
Devoluciones
Nueva continuación Task.
Excepciones
Se Task<TResult> ha eliminado .
El continuationAction argumento es null.
O bien
El scheduler argumento es null.
Comentarios
El devuelto Task no se programará para su ejecución hasta que se haya completado la tarea actual, independientemente de si se completa debido a la ejecución correcta, a errores debido a una excepción no controlada o a la salida anticipada debido a la cancelación.
Consulte también
- Biblioteca paralela de tareas (TPL)
- Programación asincrónica basada en tareas
- Encadenado de tareas mediante tareas de continuación
Se aplica a
ContinueWith<TNewResult>(Func<Task<TResult>,Object,TNewResult>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler)
Crea una continuación que se ejecuta cuando se completa el destino Task<TResult> .
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>
Public Function ContinueWith(Of TNewResult) (continuationFunction As Func(Of Task(Of TResult), Object, TNewResult), state As Object, cancellationToken As CancellationToken, continuationOptions As TaskContinuationOptions, scheduler As TaskScheduler) As Task(Of TNewResult)
Parámetros de tipo
- TNewResult
Tipo del resultado generado por la continuación.
Parámetros
Función que se va a ejecutar cuando Task<TResult> se completa. Cuando se ejecuta, el delegado se pasará la tarea completada y el objeto de estado proporcionado por el autor de la llamada como argumentos.
- state
- Object
Objeto que representa los datos que va a usar la función de continuación.
- cancellationToken
- CancellationToken
que CancellationToken se asignará a la nueva tarea.
- continuationOptions
- TaskContinuationOptions
Opciones para cuándo se programa la continuación y cómo se comporta. Esto incluye criterios, como OnlyOnCanceled, así como opciones de ejecución, como ExecuteSynchronously.
- scheduler
- TaskScheduler
TaskScheduler que se va a asociar a la tarea de continuación y que se va a usar para su ejecución.
Devoluciones
Nueva continuación Task<TResult>.
Excepciones
El scheduler argumento es null.
El continuationOptions argumento especifica un valor no válido para TaskContinuationOptions.
El elemento proporcionado CancellationToken ya se ha eliminado.
Comentarios
El devuelto Task<TResult> no se programará para su ejecución hasta que se haya completado la tarea actual, independientemente de si se completa debido a la ejecución correcta, a errores debido a una excepción no controlada o a la salida anticipada debido a la cancelación.
Cuando continuationFunctionse ejecuta , debe devolver un Task<TResult>. El estado de finalización de esta tarea se transferirá a la tarea devuelta desde la Task<TResult>.ContinueWith llamada.
Consulte también
Se aplica a
ContinueWith<TNewResult>(Func<Task<TResult>,TNewResult>, CancellationToken, TaskContinuationOptions, TaskScheduler)
Crea una continuación que se ejecuta según la condición especificada en continuationOptions.
public:
generic <typename TNewResult>
System::Threading::Tasks::Task<TNewResult> ^ ContinueWith(Func<System::Threading::Tasks::Task<TResult> ^, TNewResult> ^ continuationFunction, System::Threading::CancellationToken cancellationToken, System::Threading::Tasks::TaskContinuationOptions continuationOptions, System::Threading::Tasks::TaskScheduler ^ scheduler);
public System.Threading.Tasks.Task<TNewResult> ContinueWith<TNewResult>(Func<System.Threading.Tasks.Task<TResult>,TNewResult> continuationFunction, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskContinuationOptions continuationOptions, System.Threading.Tasks.TaskScheduler scheduler);
override this.ContinueWith : Func<System.Threading.Tasks.Task<'Result>, 'NewResult> * System.Threading.CancellationToken * System.Threading.Tasks.TaskContinuationOptions * System.Threading.Tasks.TaskScheduler -> System.Threading.Tasks.Task<'NewResult>
Public Function ContinueWith(Of TNewResult) (continuationFunction As Func(Of Task(Of TResult), TNewResult), cancellationToken As CancellationToken, continuationOptions As TaskContinuationOptions, scheduler As TaskScheduler) As Task(Of TNewResult)
Parámetros de tipo
- TNewResult
Tipo del resultado generado por la continuación.
Parámetros
Función que se va a ejecutar según la condición especificada en continuationOptions.
Cuando se ejecuta, el delegado se pasará como argumento esta tarea completada.
- cancellationToken
- CancellationToken
que CancellationToken se asignará a la nueva tarea.
- continuationOptions
- TaskContinuationOptions
Opciones para cuándo se programa la continuación y cómo se comporta. Esto incluye criterios, como OnlyOnCanceled, así como opciones de ejecución, como ExecuteSynchronously.
- scheduler
- TaskScheduler
TaskScheduler que se va a asociar a la tarea de continuación y que se va a usar para su ejecución.
Devoluciones
Nueva continuación Task<TResult>.
Excepciones
Se Task<TResult> ha eliminado .
O bien
El CancellationTokenSource objeto que creó cancellationToken ya se ha eliminado.
El continuationFunction argumento es null.
O bien
El scheduler argumento es null.
El continuationOptions argumento especifica un valor no válido para TaskContinuationOptions.
Comentarios
El devuelto Task<TResult> no se programará para su ejecución hasta que se haya completado la tarea actual, independientemente de si se completa debido a la ejecución correcta, a errores debido a una excepción no controlada o a la salida anticipada debido a la cancelación.
Cuando continuationFunctionse ejecuta , debe devolver un Task<TResult>.
Consulte también
- Biblioteca paralela de tareas (TPL)
- Programación asincrónica basada en tareas
- Encadenado de tareas mediante tareas de continuación
Se aplica a
ContinueWith<TNewResult>(Func<Task<TResult>,Object,TNewResult>, Object, TaskScheduler)
Crea una continuación que se ejecuta cuando se completa el destino Task<TResult> .
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 del resultado generado por la continuación.
Parámetros
Función que se va a ejecutar cuando Task<TResult> se completa. Cuando se ejecuta, el delegado se pasará la tarea completada y el objeto de estado proporcionado por el autor de la llamada como argumentos.
- state
- Object
Objeto que representa los datos que va a usar la función de continuación.
- scheduler
- TaskScheduler
TaskScheduler que se va a asociar a la tarea de continuación y que se va a usar para su ejecución.
Devoluciones
Nueva continuación Task<TResult>.
Excepciones
El scheduler argumento es null.
Comentarios
El devuelto Task<TResult> no se programará para su ejecución hasta que se haya completado la tarea actual, independientemente de si se completa debido a la ejecución correcta, a errores debido a una excepción no controlada o a la salida anticipada debido a la cancelación.
Consulte también
Se aplica a
ContinueWith<TNewResult>(Func<Task<TResult>,Object,TNewResult>, Object, TaskContinuationOptions)
Crea una continuación que se ejecuta cuando se completa el destino Task<TResult> .
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 del resultado generado por la continuación.
Parámetros
Función que se va a ejecutar cuando Task<TResult> se completa. Cuando se ejecuta, el delegado se pasará la tarea completada y el objeto de estado proporcionado por el autor de la llamada como argumentos.
- state
- Object
Objeto que representa los datos que va a usar la función de continuación.
- continuationOptions
- TaskContinuationOptions
Opciones para cuándo se programa la continuación y cómo se comporta. Esto incluye criterios, como OnlyOnCanceled, así como opciones de ejecución, como ExecuteSynchronously.
Devoluciones
Nueva continuación Task<TResult>.
Excepciones
El continuationFunction argumento es null.
El continuationOptions argumento especifica un valor no válido para TaskContinuationOptions.
Comentarios
El devuelto Task<TResult> no se programará para su ejecución hasta que se haya completado la tarea actual, independientemente de si se completa debido a la ejecución correcta, a errores debido a una excepción no controlada o a la salida anticipada debido a la cancelación.
Cuando continuationFunctionse ejecuta , debe devolver un Task<TResult>. El estado de finalización de esta tarea se transferirá a la tarea devuelta desde la llamada ContinueWith.
Consulte también
Se aplica a
ContinueWith<TNewResult>(Func<Task<TResult>,Object,TNewResult>, Object, CancellationToken)
Crea una continuación que se ejecuta cuando se completa el destino Task<TResult> .
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>
Public Function ContinueWith(Of TNewResult) (continuationFunction As Func(Of Task(Of TResult), Object, TNewResult), state As Object, cancellationToken As CancellationToken) As Task(Of TNewResult)
Parámetros de tipo
- TNewResult
Tipo del resultado generado por la continuación.
Parámetros
Función que se va a ejecutar cuando Task<TResult> se completa. Cuando se ejecuta, el delegado se pasará la tarea completada y el objeto de estado proporcionado por el autor de la llamada como argumentos.
- state
- Object
Objeto que representa los datos que va a usar la función de continuación.
- cancellationToken
- CancellationToken
que CancellationToken se asignará a la nueva tarea.
Devoluciones
Nueva continuación Task<TResult>.
Excepciones
El continuationFunction argumento es null.
El elemento proporcionado CancellationToken ya se ha eliminado.
Comentarios
El devuelto Task<TResult> no se programará para su ejecución hasta que se haya completado la tarea actual, independientemente de si se completa debido a la ejecución correcta, a errores debido a una excepción no controlada o a la salida anticipada debido a la cancelación.
Consulte también
Se aplica a
ContinueWith<TNewResult>(Func<Task<TResult>,TNewResult>, TaskContinuationOptions)
Crea una continuación que se ejecuta según la condición especificada en 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 del resultado generado por la continuación.
Parámetros
Función que se va a ejecutar según la condición especificada en continuationOptions.
Cuando se ejecute, el delegado se pasará la tarea completada como argumento.
- continuationOptions
- TaskContinuationOptions
Opciones para cuándo se programa la continuación y cómo se comporta. Esto incluye criterios, como OnlyOnCanceled, así como opciones de ejecución, como ExecuteSynchronously.
Devoluciones
Nueva continuación Task<TResult>.
Excepciones
Se Task<TResult> ha eliminado .
El continuationFunction argumento es null.
El continuationOptions argumento especifica un valor no válido para TaskContinuationOptions.
Comentarios
El devuelto Task<TResult> no se programará para su ejecución hasta que se haya completado la tarea actual, independientemente de si se completa debido a la ejecución correcta, a errores debido a una excepción no controlada o a la salida anticipada debido a la cancelación.
Cuando continuationFunctionse ejecuta , debe devolver un Task<TResult>.
Consulte también
- Biblioteca paralela de tareas (TPL)
- Programación asincrónica basada en tareas
- Encadenado de tareas mediante tareas de continuación
Se aplica a
ContinueWith<TNewResult>(Func<Task<TResult>,TNewResult>, CancellationToken)
Crea una continuación que se ejecuta de forma asincrónica cuando se completa el destino Task<TResult> .
public:
generic <typename TNewResult>
System::Threading::Tasks::Task<TNewResult> ^ ContinueWith(Func<System::Threading::Tasks::Task<TResult> ^, TNewResult> ^ continuationFunction, System::Threading::CancellationToken cancellationToken);
public System.Threading.Tasks.Task<TNewResult> ContinueWith<TNewResult>(Func<System.Threading.Tasks.Task<TResult>,TNewResult> continuationFunction, System.Threading.CancellationToken cancellationToken);
override this.ContinueWith : Func<System.Threading.Tasks.Task<'Result>, 'NewResult> * System.Threading.CancellationToken -> System.Threading.Tasks.Task<'NewResult>
Public Function ContinueWith(Of TNewResult) (continuationFunction As Func(Of Task(Of TResult), TNewResult), cancellationToken As CancellationToken) As Task(Of TNewResult)
Parámetros de tipo
- TNewResult
Tipo del resultado generado por la continuación.
Parámetros
Función que se va a ejecutar cuando Task<TResult> se completa. Cuando se ejecute, el delegado se pasará la tarea completada como argumento.
- cancellationToken
- CancellationToken
que CancellationToken se asignará a la nueva tarea.
Devoluciones
Nueva continuación Task<TResult>.
Excepciones
Se Task<TResult> ha eliminado .
O bien
El CancellationTokenSource objeto que creó cancellationToken ya se ha eliminado.
El continuationFunction argumento es null.
Comentarios
El devuelto Task<TResult> no se programará para su ejecución hasta que se haya completado la tarea actual, independientemente de si se completa debido a la ejecución correcta, a errores debido a una excepción no controlada o a la salida anticipada debido a la cancelación.
Consulte también
- Biblioteca paralela de tareas (TPL)
- Programación asincrónica basada en tareas
- Encadenado de tareas mediante tareas de continuación
Se aplica a
ContinueWith<TNewResult>(Func<Task<TResult>,Object,TNewResult>, Object)
Crea una continuación que se ejecuta cuando se completa el destino Task<TResult> .
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 del resultado generado por la continuación.
Parámetros
Función que se va a ejecutar cuando Task<TResult> se completa. Cuando se ejecuta, el delegado se pasará la tarea completada y el objeto de estado proporcionado por el autor de la llamada como argumentos.
- state
- Object
Objeto que representa los datos que va a usar la función de continuación.
Devoluciones
Nueva continuación Task<TResult>.
Excepciones
El continuationFunction argumento es null.
Ejemplos
En el ejemplo siguiente se crea una cadena de tareas de continuación. Cada tarea proporciona la hora actual, un DateTime objeto, para el argumento state del ContinueWith(Action<Task,Object>, Object) método . Cada DateTime valor representa la hora en la que se crea la tarea continue. Cada tarea genera como resultado un segundo DateTime valor que representa la hora en la que finaliza la tarea. Una vez finalizadas todas las tareas, el ejemplo muestra la fecha y las horas en las que se inicia y finaliza cada tarea de continuación.
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 haya completado la tarea actual, independientemente de si se completa debido a la ejecución correcta, a errores debido a una excepción no controlada o a la salida anticipada debido a la cancelación.
Consulte también
Se aplica a
ContinueWith<TNewResult>(Func<Task<TResult>,TNewResult>)
Crea una continuación que se ejecuta de forma asincrónica cuando se completa el destino Task<TResult> .
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 del resultado generado por la continuación.
Parámetros
Función que se va a ejecutar cuando Task<TResult> se completa. Cuando se ejecute, el delegado se pasará la tarea completada como argumento.
Devoluciones
Nueva continuación Task<TResult>.
Excepciones
Se Task<TResult> ha eliminado .
El continuationFunction argumento es null.
Comentarios
El devuelto Task<TResult> no se programará para su ejecución hasta que se haya completado la tarea actual, independientemente de si se completa debido a la ejecución correcta, a errores debido a una excepción no controlada o a la salida anticipada debido a la cancelación.
Consulte también
- Biblioteca paralela de tareas (TPL)
- Programación asincrónica basada en tareas
- Encadenado de tareas mediante tareas de continuación
Se aplica a
ContinueWith<TNewResult>(Func<Task<TResult>,TNewResult>, TaskScheduler)
Crea una continuación que se ejecuta de forma asincrónica cuando se completa el destino Task<TResult> .
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 del resultado generado por la continuación.
Parámetros
Función que se va a ejecutar cuando Task<TResult> se completa. Cuando se ejecute, el delegado se pasará la tarea completada como argumento.
- scheduler
- TaskScheduler
TaskScheduler que se va a asociar a la tarea de continuación y que se va a usar para su ejecución.
Devoluciones
Nueva continuación Task<TResult>.
Excepciones
Se Task<TResult> ha eliminado .
El continuationFunction argumento es null.
O bien
El scheduler argumento es null.
Comentarios
El devuelto Task<TResult> no se programará para su ejecución hasta que se haya completado la tarea actual, independientemente de si se completa debido a la ejecución correcta, a errores debido a una excepción no controlada o a la salida anticipada debido a la cancelación.
Consulte también
- TaskScheduler
- Biblioteca paralela de tareas (TPL)
- Programación asincrónica basada en tareas
- Encadenado de tareas mediante tareas de continuación