Royi Namir
Royi Namir

Reputation: 148514

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

Upvotes: 6

Views: 665

Answers (1)

Ani
Ani

Reputation: 113392

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

Upvotes: 5

Related Questions