我正在制作一个经常使用异步的 Flutter 应用程序,但它不像我理解的那样工作。所以我对 dart 中的 async 和 await 有一些疑问。下面是一个例子:
Future<int> someFunction() async {
int count = 0;
for (int i=0; i< 1000000000;i ++) {
count+= i;
}
print("done");
return count;
}
Future<void> test2() async {
print("begin");
var a = await someFunction();
print('end');
}
void _incrementCounter() {
print("above");
test2();
print("below");
}
Run Code Online (Sandbox Code Playgroud)
test2() 函数需要很多时间才能完成。对?所以我想要的是当 test2 保持他的工作运行直到完成时,一切都会继续运行而不是等待 test2()。
当我运行函数 _incrementCounter() 时,它显示结果:
以上开始完成以下结束
问题是它没有立即显示“下方”,而是等到 someFunction() 完成。
这是我想要的结果:
上面开始下面完成结束
这是预期的行为,因为 Dart 2.0 中的此更改可以在更改日志中找到:
(中断)标记为 async 的函数现在同步运行,直到第一个 await 语句。以前,它们会在任何代码运行之前在函数体顶部返回一次事件循环(问题 30345)。
在我给出解决方案之前,我想提醒您异步代码没有在另一个线程中运行,因此概念如下:
保持他的工作运行直到完成,一切都会继续运行而不是等待 test2()
很好,但在某些时候,您的应用程序将等待 test2() 完成,因为它是作为作业队列上的任务生成的,在该队列完成之前它不会让其他作业运行。如果您想要没有减速的体验,您要么将作业拆分为多个较小的作业,要么生成一个隔离(在另一个线程中运行)来运行计算,然后返回结果。
这是让您的示例工作的解决方案:
Future<int> someFunction() async {
int count = 0;
for (int i=0; i< 1000000000;i ++) {
count+= i;
}
print("done");
return count;
}
Future<void> test2() async {
print("begin");
var a = await Future.microtask(someFunction);
print('end');
}
void _incrementCounter() {
print("above");
test2();
print("below");
}
main() {
_incrementCounter();
}
Run Code Online (Sandbox Code Playgroud)
通过使用Future.microtask构造函数,我们正在调度someFunction()作为另一个任务运行。这使得“await”将等待,因为它将是异步调用的第一个真实实例。
| 归档时间: |
|
| 查看次数: |
1645 次 |
| 最近记录: |