I have this sample code :
Task<int> t1= new Task<int>(()=>1);
t1.ContinueWith(r=>1+r.Result).ContinueWith(r=>1+r.Result);
t1.Start();
Console.Write(t1.Result); //1
It obviously return the Result
from the t1
task. ( which is 1)
But how can I get the Result
from the last continued task ( it should be 3
{1+1+1})
A continuation task (also known just as a continuation) is an asynchronous task that's invoked by another task, known as the antecedent, when the antecedent finishes.
ContinueWith(Action<Task,Object>, Object, TaskScheduler)Creates a continuation that receives caller-supplied state information and executes asynchronously when the target Task completes.
The ContinueWith function is a method available on the task that allows executing code after the task has finished execution. In simple words it allows continuation. Things to note here is that ContinueWith also returns one Task. That means you can attach ContinueWith one task returned by this method.
Console. WriteLine("Press any key to stop the task\n");
ContinueWith
itself returns a task - Task<int>
in this case. You can do anything (more or less - you can't manually Start
a continuation, for example) you wish with this task that you could have done with the 'original' task, including waiting for its completion and inspecting its result.
var t1 = new Task<int>( () => 1);
var t2 = t1.ContinueWith(r => 1 + r.Result)
.ContinueWith(r => 1 + r.Result);
t1.Start();
Console.Write(t1.Result); //1
Console.Write(t2.Result); //3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With