Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the Task's Result property unavailable for non-generic Task (C# 4.0+)?

I am trying to get grasp of .NET 4.0+ Task Parallel Library concepts...

In the following C# 4.0 code snippet:

Task t = Task.Factory.StartNew(() =>
{
   Console.WriteLine("I am the task");
   return "res1";
});

why compiler doesn't (and run-time either) produce any error if the return cannot be used unless generic Task used instead:

Task<string> t = Task.Factory.StartNew(() =>
{
   Console.WriteLine("I am the task");
   return "res1";
});

Or it (returned object) can be used?

Do I understand correctly that <string> in Task<string> is needed only for detecting or assuring the type of return (ed object) or of t.Result?
Or there are any other hidden from me necessities except this?

Why this type cannot cannot be determined from the type of returned object?
I.e. why is the Result property of a task unavailable for non-generic tasks?

like image 571
Fulproof Avatar asked Mar 12 '13 11:03

Fulproof


1 Answers

The non-generic Task does not have a Result property because it represents a process that does not produce a result.

Your code creates a Task<string> in both cases, but in the first case you cast it to a Task (Task<string> derives from Task, so that's legal) and so you lose the ability to refer to the result.

You can see this directly with:

Task t = Task.Factory.StartNew(() =>
{
   Console.WriteLine("I am the task");
   return "res1";
});

var genericTask = t as Task<string>; // genericTask will be non-null
var result = genericTask.Result;     // and you can access the result
like image 194
Jon Avatar answered Sep 19 '22 00:09

Jon