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?
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
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