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

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

它还提到Microtask队列总是首先运行,然后是事件队列.

这个文档很旧,似乎是面向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

但是如果所有Microtasks都要在下一个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’的情况下拨打电话时的一些奖励事实:
根据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()

相关文章

这篇文章主要讲解了“FlutterComponent动画的显和隐怎么实现...
这篇文章主要讲解了“flutter微信聊天输入框功能如何实现”,...
本篇内容介绍了“Flutter之Navigator的高级用法有哪些”的有...
这篇文章主要介绍“Flutter怎么使用Android原生播放器”,在...
Flutter开发的android端如何修改APP名称,logo,版本号,具体...
Flutter路由管理初识路由概念一.路由管理1.1.Route1.2.Mater...