【发布时间】:2019-02-16 05:58:45
【问题描述】:
在什么情况下你会在方法签名中不使用async而返回Task<T>?
我在下面的代码中有这样的方法,但我无法理解发生了什么。
为什么我下面的示例代码没有执行任何await 语句?
IE。为什么Console.WriteLine("4)"); 和Console.WriteLine("3)"); 和return x; 永远不会被执行?
class Program
{
static void Main(string[] args)
{
TestAsync testAsync = new TestAsync();
testAsync.Run();
Console.Read();
}
}
public class TestAsync
{
public async void Run()
{
Task<int> resultTask = GetInt();
Console.WriteLine("2)");
int x = await resultTask;
Console.WriteLine("4)");
}
public async Task<int> GetInt()
{
Task<int> GetIntAfterLongWaitTask = GetIntAfterLongWait();
Console.WriteLine("1)");
int x = await GetIntAfterLongWaitTask;
Console.WriteLine("3)");
return x;
}
public Task<int> GetIntAfterLongWait()
{
Task.Run(() =>
{
for (int i = 0; i < 500000000; i++)
{
if (i % 10000000 == 0)
{
Console.WriteLine(i);
}
}
});
Console.WriteLine("Returning 23");
return new Task<int>(() => 23);
}
}
/*
Output is:
Returning 23
1)
2)
<list of ints>
*/
【问题讨论】:
-
Task<T>是可以通过任何方法返回的合法类型。如果它前面没有async关键字,那么您根本无法在方法中使用await某些东西。 -
但是为什么编译器不给出警告/编译错误呢?
-
如果你的方法只需要返回一个任务而不需要等待它本身,你就可以使用它,例如因为它是方法中的最后一条语句。话虽如此,您通常不应该使用
new Task。如果要返回包装为任务的值,即完成的任务结果,请使用Task.FromResult(23),它的优点是不会用完像Task.Run和可能的new Task这样的线程。 -
@Backwards_Dave - 阅读blogs.msdn.microsoft.com/pfxteam/2011/01/13/await-anything
标签: c# async-await task