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