flutter-异步编程

2021-04-05  本文已影响0人  小源子2016

Dart执行(运行在UI task runner ,root isolate)

image.png
library flutter_package3;

import 'dart:async';
void isolateTest() async{
  print('isolateTest #1 of 2');
  scheduleMicrotask(() => print('microtask #1 of 3'));
  //使用delay方式,是将此task放到queue的尾部,
  //若前面有耗时操作,不一定能准时执行
  await new Future.delayed(new Duration(seconds:1),
          () => print('future #1 (delayed)'));

  //使用then,是表示在此task执行后立刻执行
  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(
           //注意这种写法阻塞下一个then函数
          () => print('future #3a (a new future)')))
      .then((_) => print('future #3b'));

  new Future(() => print('future #4 of 4'))
      .then((_) {
      // 注意:这种写法不阻塞一一个then函数
     //若加个return 就变成阻塞了
     new Future(() => print('future #4a'));
  })
      .then((_) => print('future #4b'));
  scheduleMicrotask(() => print('microtask #3 of 3'));
  print('isolateTest #2 of 2');
}

//在main中调用
void main() {
  isolateTest();
  print('main');
}

CUP耗时和IO耗时

void _incrementCounter() async {
  var future = await new Future(() {
    var i = 0;
    while (true) {
      print("${i++}");
      if (i > 200000) {
        break;
      }
    }
    return new Dio().get('http://www.baidu.com');
  });
  setState(() {
    _counter = future.hashCode;
  });
}

在future里面做一个20万次打印的操作,这个时候我们再次点击floatingActionButton,然后点击IconButton,UI就会卡顿。
这里就要分IO耗时和CPU耗时了,网络请求和文件读取一类的操作不会使用CPU,而是纯等待IO而已,所以我们CPU可以去event Queue里取其他Task执行,而CPU耗时就是实实在在的CPU计算了。由于Dart是单线程的,Futrue的异步并不是真正的异步,所以会造成卡顿。

Dart是单线程,没有真正的异步,需要避免CPU耗时,IO耗时没关系的
https://www.jianshu.com/p/3f99e4d302c3

上一篇 下一篇

猜你喜欢

热点阅读