user3486941
user3486941

Reputation: 381

ContinueWith and Result of the task

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?

Upvotes: 38

Views: 57682

Answers (3)

BRAHIM Kamel
BRAHIM Kamel

Reputation: 13755

ContinueWith will create a new task when the first task complete execution that's may or not use the same thread because it's depend on the task scheduler

You can use ContinueWith<TResult>(Func<Task, TResult>) in order get the result from the second task

your code will look something like this

 static void Main(string[] args)
        {

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

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

            Console.Read();

        }

Upvotes: 14

Simon Whitehead
Simon Whitehead

Reputation: 65059

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.

Upvotes: 15

Yurii
Yurii

Reputation: 4911

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());

Upvotes: 50

Related Questions