This page looks best with JavaScript enabled

Dart中的异步编程

 ·  ☕ 1 min read

Isolate

Dart 中的线程概念是 Isolate, 一个在操作系统 Thread 只上的封装, 默认 Dart 程序会在一个 Isolate 中顺序执行代码.

  • Isolate 中的代码是按顺序执行
  • 任何 Dart 程序的并发都是运行多个 Isolate 的结果
  • 因为 Isolate 之间不会共享内存,没有竞争的可能性所以不需要锁,也就不用担心死锁的问题
  • Isolate 之间不能直接通信, 可以通过 DartVM 提供的 SendPort 通道通信

DartVM 运行模式

  • 单线程执行: 一个 Isolate 拥有一个事件循环
  • 一个事件循环和两个队列
  • 事件循环只由单个线程执行 => 没有同步和锁的问题
  • microtask queue 优先级高于 event queue
  • 队列里的方法被执行时会阻塞整个程序
  • 创建一个 Future 就是向 event queue 提交一个事件
  • 通过 Future.microtaskscheduleMicrotask 向 microtask queue 提交一个事件

Question

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import 'dart:async';

void main() {
  print('#1');
  scheduleMicrotask(() => print('#2'));

  Future.delayed(Duration(seconds: 1), () => print('#3')); // 延迟1秒再回调
  Future(() => print('#4'));
  Future(() => print('#5'));

  scheduleMicrotask(() => print('#6'));

  print('#7');
}

结果是? (运行试试吧)

Support the author with
alipay QR Code
wechat QR Code

Yang
WRITTEN BY
Yang
Developer