dart - 事件队列和微任务队列

标签 dart flutter

在 Dart 文档中 The Event Loop and Dart (2013)它提到任何 Future 都被添加到 Event 队列中。

它还提到 Microtask 队列总是首先运行,然后是 Event 队列。

这个文档很旧,而且似乎面向 Web 开发,所以我不确定这对于 Flutter 是否与我编写此代码时不同。

Future<String> myFunction() => new Future.value('Hello');
Future<String> myFunction2() => new Future.value('Hello2');
Future<void> mainTest() async {
  debugPrint("Sync1");  
  myFunction().then(debugPrint);
  scheduleMicrotask(() { debugPrint("Microtask"); });
  myFunction2().then(debugPrint);  
  debugPrint("Sync2");
}

我得到了

的输出
I/flutter ( 6731): Sync1
I/flutter ( 6731): Sync2
I/flutter ( 6731): Hello
I/flutter ( 6731): Microtask
I/flutter ( 6731): Hello2

但如果所有的 Microtask 都应该在下一个 Event 循环之前运行,不应该是这样吗?

I/flutter ( 6731): Sync1
I/flutter ( 6731): Sync2
I/flutter ( 6731): Microtask // This running first before the Futures?
I/flutter ( 6731): Hello
I/flutter ( 6731): Hello2

最佳答案

如果您在调用方法而不调用 .then

时就会出现这种情况

A way to add a task to the microtask queue is to invoke then() on a Future that’s already complete.

所以当你调用 myFunction().then(print); future 会被添加到微任务队列中。

在没有 '.then' 的情况下调用时的一些额外事实: 根据docs有 2 个错误。 这些错误已修复,但问题仍然存在 :(

The upshot of these bugs: The first task that you schedule with scheduleMicrotask() seems like it’s on the event queue.

A workaround is to put your first call to scheduleMicrotask() before your first call to new Future()

关于dart - 事件队列和微任务队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54180637/

相关文章:

android - Play 商店登录失败

dart - 以编程方式设置核心下拉元素的 PaperItem 标签

flutter - 可以用吗??在这种情况下是运营商?

flutter - 在 Flutter 中将 BASE64 字符串转换为图像

flutter - 无法获取Flutter AppBar主题变量

dart - 使用 Futures 在 Flutter 中加载 config.json

keyboard - flutter 数字键盘未完成按钮

Flutter 如何从 Text 小部件中删除不需要的填充?

dart - 升级到 Dart2/Angular5 导入 template.dart 时出错

flutter - 如何从单独的类调用 flutter 对话框?