Flutter-Daily-Interview icon indicating copy to clipboard operation
Flutter-Daily-Interview copied to clipboard

第004期 Future和microtask执行顺序

Open wyufeng02 opened this issue 5 years ago • 1 comments

wyufeng02 avatar Aug 03 '19 16:08 wyufeng02

MricroTask

Dart 中事件机制的实现 :Main isolate 中有一个Looper,但存在两个Queue:Event Queue 和 Microtask Queue 。

Dart 中事件的执行顺序:Main > MicroTask > EventQueue。

在 Main 中写代码将最先执行; 执行完 Main 中的代码,然后会检查并执行 Microtask Queue 中的任务, 通常使用 scheduleMicrotask 将事件添加到 MicroTask Queue 中; 最后执行 EventQueue 队列中的代码,通常使用 Future 向 EventQueue加入时间,也可以使用 async 和 await 向 EventQueue 加入事件。

image

Future 先进先出

Future提供链式调用

new Future (() => print('拆分任务_1'))
    .then((i) => print('拆分任务_2'))
    .then((i) => print('拆分任务_3'))
    .whenComplete(()=>print('任务完成'));

多Future 和 多micTask 的执行顺序

void testScheduleMicrotatsk() {
  scheduleMicrotask(() => print('Mission_1'));

//注释1
  new Future.delayed(new Duration(seconds: 1), () => print('Mission_2'));

//注释2
  new Future(() => print('Mission_3')).then((_) {
    print('Mission_4');
    scheduleMicrotask(() => print('Mission_5'));
  }).then((_) => print('Mission_6'));

//注释3
  new Future(() => print('Mission_7'))
      .then((_) => new Future(() => print('Mission_8')))
      .then((_) => print('Mission_9'));

//注释4
  new Future(() => print('Mission_10'));

  scheduleMicrotask(() => print('Mission_11'));

  print('Mission_12');
}


输出结果

I/flutter (19025): Mission_12
I/flutter (19025): Mission_1
I/flutter (19025): Mission_11
I/flutter (19025): Mission_3
I/flutter (19025): Mission_4
I/flutter (19025): Mission_6
I/flutter (19025): Mission_5
I/flutter (19025): Mission_7
I/flutter (19025): Mission_10
I/flutter (19025): Mission_8
I/flutter (19025): Mission_9
Syncing files to device MIX 3...
I/flutter (19025): Mission_2

Natoto avatar Aug 06 '19 10:08 Natoto