我在Dart遇到async
方法和Future
的问题。
我想我做错了什么,但我不知道是什么。
我想弄清楚Future
和async
之间的区别,并了解事件循环的工作原理。我阅读了文档和很多关于它的文章。我以为我理解了所以我试着编写一些代码来创建一个带有Future
调用的sleep()
对象。
首先,我尝试使用Future
,我认为它的行为应该如下:
main(List<String> arguments) {
print('before future');
test_future();
print('after future');
}
test_future() {
Future (() {
print('Future active before 5 seconds call');
sleep(Duration(seconds: 5));
print('Future active after 5 seconds call');
}).then((_) => print("Future completed"));
}
所以这回来了:
我认为这一切都很正常。
现在,我正在尝试用async
做同样的事情。从文档中,将async
关键字添加到函数使其立即返回Future
。
所以我写了这个:
main(List<String> arguments) {
print('before future 2');
test().then((_) => print("Future completed 2"));
print('after future 2');
}
test() async {
print('Future active before 5 seconds call');
sleep(Duration(seconds: 5));
print('Future active after 5 seconds call');
}
通常,在调用test().then()
时,它应该将test()
的内容放在事件队列中并立即返回Future
但不是。行为是这样的:
如果我没有正确使用async
或者有什么问题,有人可以解释一下吗?
最好
你应该知道sleep()只是阻止了整个程序。 sleep()与事件循环或异步执行无关。也许您想要使用:
await Future.delayed(const Duration(seconds: 5), (){});
异步系统调用不会阻止隔离。事务队列仍在处理中(在调用系统调用后立即继续)。如果你进行同步系统调用,它们会像睡眠一样阻止。
在系统调用的dart:io
中经常存在同步和异步变体,如api.dartlang.org/stable/2.2.0/dart-io/File/readAsLinesSync.html。即使sleep
没有同步后缀,它也是同步的,无法解决。您可以使用如上所示的Future.delayed()
以异步方式获得效果。