考虑这个(教科书)样本飞镖码:
private void Grid_Checked(object sender, RoutedEventArgs e)
{
Storyboard sb = new Storyboard();
double height = 100; //set whatever height you want here
DoubleAnimation animation = new DoubleAnimation() { From = 50.0, To = height, Duration = TimeSpan.FromSeconds(1) };
Storyboard.SetTargetProperty(animation, new PropertyPath("(Grid.Height)"));
Storyboard.SetTarget(animation, sender as Grid);
sb.Children.Add(animation);
sb.Begin();
}
我知道await将等待未来“昂贵的A”的结果在继续之前完成。
但我不明白为什么main()本身必须声明为异步?显然你必须这样做,否则程序将无法编译。但是为什么同步方法不能等待异步调用的结果呢?
我知道这一定是一个新手问题,但我还没有找到答案。
答案 0 :(得分:5)
在async
/ await
之前,这只是前一段时间才添加到Dart,你会写得像
main() {
var result = expensiveA()
.then((_) => expensiveB())
.then((_) => expensiveC()); // the Future returned by expensiveC will be returned because `doSomethingWith` is not awaited in your code
result.then(doSomethingWith);
return result;
}
异步调用返回Future
,您可以将函数传递给它在异步调用完成时调用的then
方法。
此代码
main() async {
await expensiveA();
await expensiveB();
doSomethingWith(await expensiveC()); // doSomethingWith is not awaited
}
在执行之前,将其重写为与第一个代码块中的代码类似的内容。
这表明async
/ await
并未改变代码的性质,只会将语法更改为更像同步代码的内容。
async
是一个标记,需要重写方法中的代码,并且此标记允许使用await
,而不重写await
没有任何意义。
async
隐式返回上一个await
ed Future
,以便调用者能够await
完成此Future
。
由于返回Future
,因此强模式要求返回类型匹配。
答案 1 :(得分:2)
为什么同步方法不能等待异步调用的结果? 因为这意味着阻止,直到昂贵的通话结束。
然而Dart是single threaded with event loop,因此使用简单的方法来阻止整个Dart应用会非常危险。