2012-01-20 7 views

Respuesta

16

El TPL y la clase Task son muy diferentes de la promesa de jQuery.

A Task es realmente más como la acción original. Si desea ejecutar algo cuando se completa la tarea, debe usar continuación en la Tarea. Esto parecería efectivamente más como:

Task someTask = RunMethodAsync(); 
someTask.ContinueWith(t => 
{ 
    // This runs after the task completes, similar to how promise() would work 
}); 

Si desea continuar en múltiples tareas, puede utilizar Task.Factory.ContinueWhenAll o Task.Factory.ContinueWhenAny hacer continuaciones que funciona en múltiples tareas.

5

Eso suena como una continuación, entonces use .ContinueWith(callback); o en C# 5.0, simplemente await, es decir

var task = /*...*/ 
var result = await task; 
// everything here happens later on, when it is completed 
// (assuming it isn't already) 

API diferente, pero yo creo hace lo que usted está pidiendo (un poco difícil estar seguro ... No estoy totalmente seguro de entender la pregunta)

5

Parece que estás buscando TaskCompletionSource:

var tcs = new TaskCompletionSource<Args>(); 

var obj = new SomeApi(); 

// will get raised, when the work is done 
obj.Done += (args) => 
{ 
    // this will notify the caller 
    // of the SomeApiWrapper that 
    // the task just completed 
    tcs.SetResult(args); 
} 

// start the work 
obj.Do(); 

return tcs.Task; 

El código se toma aquí: When should TaskCompletionSource<T> be used?