我在达特有这样的密码:
Future<void> dataProcessAsync() async {
await Future.delayed(Duration(seconds: 2));
print("Process Completed!");
}
void main() {
print("Process 1");
print("Process 2");
dataProcessAsync();
print("Process 3");
print("Process 4");
}一切都运行得很好,而且是异步的。结果如预期(流程1-过程2-过程3-过程4-过程完成!)
但是当我像这样写代码时:
Future<void> dataProcessAsync() async {
for(int i = 1; i <= 10000000000; i++){}
print("Process Completed!");
}
void main() {
print("Process 1");
print("Process 2");
dataProcessAsync();
print("Process 3");
print("Process 4");
}它不能异步工作。它等待dataProcessAsync()相当长的时间,然后继续处理3。(流程1-流程2-流程完成!-流程3-流程4)
有人能告诉我发生了什么事以及如何解决这个问题吗?
发布于 2021-11-30 09:21:28
async方法在第一个await之前同步运行。如果该方法从未到达await,它将运行到完成,并返回同步填充的Future。
这是由Dart网页设计和描述的:
是一个
async函数,在第一个await关键字之前同步运行。这意味着在async函数体中,第一个await关键字之前的所有同步代码都会立即执行。
https://dart.dev/codelabs/async-await#execution-flow-with-async-and-await
https://stackoverflow.com/questions/70166788
复制相似问题