未来和异步行为是不一样的,我不明白

问题描述 投票:1回答:1

我在Dart遇到async方法和Future的问题。

我想我做错了什么,但我不知道是什么。

我想弄清楚Futureasync之间的区别,并了解事件循环的工作原理。我阅读了文档和很多关于它的文章。我以为我理解了所以我试着编写一些代码来创建一个带有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"));
}

所以这回来了:

  1. 在将来打印
  2. 创建一个future对象,将其放入事件队列并立即返回
  3. 将来打印
  4. 从事件队列中调用future的代码
  5. 5秒前打印
  6. 等5秒
  7. 5秒后打印*
  8. 打印未来完成

我认为这一切都很正常。

现在,我正在尝试用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但不是。行为是这样的:

  1. 在未来之前打印2
  2. 调用test()函数(应该返回一个未来我认为,但代码现在执行)
  3. 5秒前打印
  4. 等待5秒钟
  5. 5秒后打印
  6. 打印未来完成2
  7. 将来打印2

如果我没有正确使用async或者有什么问题,有人可以解释一下吗?

最好

asynchronous dart async-await future
1个回答
2
投票

你应该知道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()以异步方式获得效果。

© www.soinside.com 2019 - 2024. All rights reserved.