可以说我跑RunSynchron()
。在这种情况下,它运行Delay()
,暂停10秒,然后继续执行程序。完成Delay()
后,它将为if
-语句返回值1。但为什么我必须退回Task<int>
而不是int
?为什么要返回任务<int>而不是int? (异步&等待)
class Synchron
{
public async void RunSynchron()
{
var delay = this.Delay();
Console.WriteLine("Now we wait...");
Console.WriteLine("But we can continue with our work");
if(await delay == 1)
Console.WriteLine("Now it's done");
}
public async Task<int> Delay()
{
await Task.Delay(10000);
return 1;
}
}
这是编译器将结果包装到适当位置的方式MT环境 - 保留结果,以便知道它将从另一个线程进入。在MT环境下工作可以节省大量时间,结果仍然是一个整数! –
http://blog.stephencleary.com/2012/02/async-and-await.html –