事件队列和微任务队列

Ada*_*ley 9 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");
}
Run Code Online (Sandbox Code Playgroud)

我得到一个输出

I/flutter ( 6731): Sync1
I/flutter ( 6731): Sync2
I/flutter ( 6731): Hello
I/flutter ( 6731): Microtask
I/flutter ( 6731): Hello2
Run Code Online (Sandbox Code Playgroud)

但是如果所有的微任务都应该在下一个事件循环之前运行,不应该是这样吗?

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
Run Code Online (Sandbox Code Playgroud)

Nut*_*uts 5

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

\n\n
\n

将任务添加到微任务队列的一种方法是在已经完成的\n Future 上调用 then() 。

\n
\n\n

因此,当您调用 myFunction().then(print);future 时,就会将其添加到微任务队列中。

\n\n

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

\n\n
\n

这些错误的结果是:您使用scheduleMicrotask() 安排的第一个任务看起来像是事件队列中的\xe2\x80\x99s。

\n\n

解决方法是在第一次调用 new Future() 之前\n 第一次调用 ScheduleMicrotask()

\n
\n