gpt4 book ai didi

dart - Dart中的异步/等待

转载 作者:行者123 更新时间:2023-12-03 03:08:53 27 4
gpt4 key购买 nike

我正在制作一个使用异步的Flutter应用程序,但它的工作方式不像我对它的了解。所以我对异步和在 Dart 中等待有一些疑问。这是一个例子:

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");
}

test2()函数将花费大量时间。对?所以我想要的是,当test2保持他的工作运行直到完成时,一切都会继续运行,而不是等待test2()。

当我运行函数_incrementCounter()时,它显示结果:

above begin done below end



问题在于它没有立即显示“在下面”,而是等到someFunction()完​​成。

这是我想要的结果:

above begin below done end

最佳答案

这是预期的行为,因为Dart 2.0中的此更改可以在更改日志中找到:

(Breaking) Functions marked async now run synchronously until the first await statement. Previously, they would return to the event loop once at the top of the function body before any code runs (issue 30345).



在给出解决方案之前,我想提醒您,异步代码未在另一个线程中运行,因此其概念是:

keep his work running until done, everything will keep running and not wait for 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();
}

通过使用Future.microtask构造函数,我们可以将someFunction()调度为作为另一个任务运行。这使得“等待”将要等待,因为它将是异步调用的第一个真实实例。

关于dart - Dart中的异步/等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57916757/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com