1
考虑下面的代码片段,其中MyMethod
及其异步版本MyMethodAsync
被称为以不同的方式:为什么在异步函数使用Task.Run不返回任务<Task<T>>
using System;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static int MyMethod()
{
System.Threading.Thread.Sleep(1000);
return 42;
}
static async Task<int> MyMethodAsync()
{
await Task.Delay(1000);
return 42;
}
static void Main(string[] args)
{
var result1 = MyMethod(); // int
var result2 = MyMethodAsync(); // Task<int>
var result3 = Task.Run(() => MyMethod()); // Task<int>
var result4 = Task.Run(() => MyMethodAsync()); // Task<int>
}
}
}
在每一种情况下,我已评论返回类型。
问题是为什么result4
的类型也是Task<int>
?不应该是Task<Task<int>>
?
顺便说一句,是否有任何情况下调用异步方法Task.Run
可能是有益的?