Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# ContinueWith and Result of the task

Tags:

c#

I use this code

    public static void Main()
    {
        Task<int> t = new Task<int>(() => { return 43; });
        t.Start();
        t.ContinueWith((i) => {return i.Result * 2; });

        Console.WriteLine("i = {0}", t.Result.ToString());

        Console.Read();
    }

And I notice that t.Result equals 43 instead of 86. If I print something in the ContinueWith it appears in the Console. Why the Result is not modified by the ContinueWith?

like image 256
user3486941 Avatar asked Apr 01 '14 21:04

user3486941


2 Answers

That's because ContinueWith creates completely new task, result of which you ignore, and instead print the result of the first one, which is rightfully 43. Try the following snippet:

Task<int> t = new Task<int>(() => { return 43; });
t.Start();
var t2 = t.ContinueWith((i) => {return i.Result * 2; });

Console.WriteLine("i = {0}", t2.Result.ToString());
like image 200
Yurii Avatar answered Oct 22 '22 19:10

Yurii


The other two answers are correct. There is another Task returned via ContinueWith. If you don't care about each individual step.. then your code can become much smaller by assigning the value of the ContinueWith after chaining them:

var t = Task.Run(() => 43)
        .ContinueWith(i => i.Result * 2);

// t.Result = 86

You will find that a lot of task-based code follows this. It isn't often that you will create and start individual Task instances when you're chaining ContinueWith on the end.

like image 13
Simon Whitehead Avatar answered Oct 22 '22 20:10

Simon Whitehead