简体   繁体   中英

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

Task<T> inherits from Task . In both cases you're actually creating a Task<T> , but in the first case you're implicitly casting it to Task , which doesn't have the Result property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM