事件队列和微任务队列 [英] Event Queues and Microtask Queues
问题描述
在Dart文档中事件循环和Dart(2013)提到任何 Future
都会添加到 Event
队列中.
In the Dart documentation The Event Loop and Dart (2013) it mentions that any Future
is added to the Event
queue.
它还提到 Microtask
队列应始终首先运行,然后是 Event
队列.
It also mentions that Microtask
queues are meant to always run first, then Event
queues.
该文档较旧,似乎适合于Web开发,因此我不确定Flutter是否与我编写此代码时有所不同.
This documentation is old, and seems geared towards web development so I'm not sure if this is different for Flutter as when I do this code.
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
但是,如果所有微任务都打算在下一个事件循环之前运行,不是吗?
But if all Microtasks were meant to be run before the next Event loop, shouldn't it be this?
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添加到微任务队列中.
So when you call myFunction().then(print);
future is added to microtask queue.
在没有' .then
'的情况下拨打电话时的一些事实:根据 docs ,有2个错误.这些错误已修复,但问题仍然存在:(
Some bonus facts for the cases when calling without '.then
':
According to the docs there were 2 bugs. These bugs were fixed, but the issue still remains :(
这些错误的结果:您计划的第一个任务scheduleMicrotask()似乎在事件队列中.
The upshot of these bugs: The first task that you schedule with scheduleMicrotask() seems like it’s on the event queue.
一种解决方法是将您的第一个调用放在scheduleMicrotask()之前您第一次致电new Future()
A workaround is to put your first call to scheduleMicrotask() before your first call to new Future()
这篇关于事件队列和微任务队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!