在 Dart并发编程一文中,咱们了解到,在isolate,经过event-loop来处理event-queue中的事情的。

event-loop。
Dart’s event loop
每一个isolate都有一个eventloop,eventloop具有两个队列:eventqueue和microtaskqueue。
-
event queue: 包括一切的外部事情,比如 I/O,制作事情,Timer,isolate之间的通讯等等。
-
micro task: 微使命队列是必要的,由于有些
event在完成时,需要在处理下一轮event queue之前,继续履行某些处理。
event queue里面包括了Dart代码的event和一些来自操作系统的event,micro task queue中的使命只能来自于Dart代码。
如下图所示,在Dart代码中,当履行main()后,event loop开端运转作业。首要依照FIFO的顺序,履行Microtask queue中的使命,直到全部履行完成。紧接着开端处理event queue中的event。

‼️非常重要的一点:当event loop处理Micro task queue中的使命时,event queue中的event是不能处理的,假如在main isolate中,就会导致App的UI不能重绘,无法响应用户事情。
怎么创建一个Task
1, 回来Future的办法,会将其添加到event queue的队尾中。
2, 使用scheduleMicrotask()函数,会将这个使命添加到micro task queue中。
怎么选择microtask queue和 event queue
原则是 尽可能的使用Future,在event queue中添加事情,尽可能的让micro task queue中的task少。能尽快的处理event queue中的事情,能让App更好的响应和用户的交互。
假如需在处理event queue中的event之前需要完成某个使命,咱们应该立刻履行该函数,假如不能能当即履行该函数,就使用scheduleMicrotask()办法,将该事情放入micro task queue中。

测试示例
示例一
调查以下代码,其运转成果怎么呢?
import 'dart:async';
main() {
print('main #1 of 2'); // 1
scheduleMicrotask(() => print('microtask #1 of 2')); // 2
new Future.delayed(new Duration(seconds:1), // 3
() => print('future #1 (delayed)')); // 4
new Future(() => print('future #2 of 3')); // 3
new Future(() => print('future #3 of 3')); // 3
scheduleMicrotask(() => print('microtask #2 of 2')); // 2
print('main #2 of 2'); // 1
}
运转成果:
main #1 of 2
main #2 of 2
microtask #1 of 2
microtask #2 of 2
future #2 of 3
future #3 of 3
future #1 (delayed)
- 1, 首要会履行 main()中的代码,将 2处的代码放入
micro task queue中,将 3 处的代码放入event queue中, 将 4 处的代码 放入下一个event queue中。 - 2,履行
micro task queue中的使命 - 3,履行
event queue中的事情,并进入下一个循环。
示例二
import 'dart:async';
main() {
print('main #1 of 2');
scheduleMicrotask(() => print('microtask #1 of 3'));
new Future.delayed(new Duration(seconds:1),
() => print('future #1 (delayed)'));
new Future(() => print('future #2 of 4'))
.then((_) => print('future #2a'))
.then((_) {
print('future #2b');
scheduleMicrotask(() => print('microtask #0 (from future #2b)'));
})
.then((_) => print('future #2c'));
scheduleMicrotask(() => print('microtask #2 of 3'));
new Future(() => print('future #3 of 4'))
.then((_) => new Future(
() => print('future #3a (a new future)')))
.then((_) => print('future #3b'));
new Future(() => print('future #4 of 4'));
scheduleMicrotask(() => print('microtask #3 of 3'));
print('main #2 of 2');
}
输入成果如下
main #1 of 2
main #2 of 2
microtask #1 of 3
microtask #2 of 3
microtask #3 of 3
future #2 of 4
future #2a
future #2b
future #2c
future #3 of 4
future #4 of 4
microtask #0 (from future #2b)
future #3a (a new future)
future #3b
future #1 (delayed)
经过event loop的事情队列状态,咱们就可以清晰的了解为什么会是这个输出成果了

参阅:
本文参阅 The event loop and Dart。
