为什么Task的Result属性对于非泛型任务(C#4.0+)不可用?

Ful*_*oof 9 .net c# multithreading task-parallel-library c#-4.0

我试图掌握.NET 4.0+任务并行库概念......

在以下C#4.0代码段中:

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

为什么编译器没有(和运行时)如果不能使用返回产生任何错误,除非使用通用任务:

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

或者它(返回的对象)可以使用?

做正确地明白的是<string>Task<string>仅需要用于检测或确保返回(编辑对象)的类型或t.Result
或者除了这个以外还有其他隐藏的必需品吗?

为什么这种类型不能从返回对象的类型中确定?
也就是为什么任务的Result属性不可用于非通用任务?

Jon*_*Jon 17

非泛型Task不具有Result属性,因为它表示产生结果的进程.

您的代码Task<string>在两种情况下都会创建一个,但在第一种情况下,您将其转换为Task(Task<string>派生自Task,因此这是合法的),因此您将失去引用结果的能力.

你可以直接看到这个:

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
Run Code Online (Sandbox Code Playgroud)

  • @Fulproof这是概念性的东西。在异步/任务世界中,“任务”在概念上大致等同于“无效”返回类型,而“任务&lt;T&gt;”等同于“ T”返回类型。现在,给定方法`void Foo()`,您将不会尝试执行`var result = Foo();`,对吗?:) (2认同)