Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the result for the last Task<> ( continuation)?

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})

like image 717
Royi Namir Avatar asked May 18 '13 06:05

Royi Namir


People also ask

What is a continuation Task?

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.

What does calling Task ContinueWith () do?

ContinueWith(Action<Task,Object>, Object, TaskScheduler)Creates a continuation that receives caller-supplied state information and executes asynchronously when the target Task completes.

What is ContinueWith C#?

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.

How do you end a Task in C#?

Console. WriteLine("Press any key to stop the task\n");


1 Answers

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
like image 68
Ani Avatar answered Oct 11 '22 09:10

Ani