Dart中的event loop
在 Dart并发编程一文中,我们了解到,在isolate
,通过event-loop
来处理event-queue
中的事件的。
本篇文章我们一起来探讨Dart中的
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。
转载自:https://juejin.cn/post/7098747387757199368