Flutter

flutter中compute和isolate

2021-03-19  本文已影响0人  xmb

dart中的isolate比较重量级,IsolateUI线程传输比较复杂,flutterfoundation中封装了一个轻量级的compute操作。

_count = await compute(countEven, 1000000000);

每次调用,都相当于创建了一个isolate,如果频繁使用的话,CPU性能、内存占用消耗也很大。

-isolate的使用:

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int myCount = 0;

  void test() async {
    myCount = await isolateCountEven(100, 2);
    setState(() {});
  }

  // 计算偶数的个数
  static int countEven(int num1, int num2) {
    int count = 0;
    while (num1 > 0) {
      if (num1 % 2 == 0) {
        count++;
      }
      num1--;

      num1 -= num2;
      print('$count');
    }
    return count;
  }

  static Future<dynamic> isolateCountEven(int num1, int num2) async {
    final response = ReceivePort();
    await Isolate.spawn(countEvent2, response.sendPort);

    final sendPort = await response.first;
    final answer = ReceivePort();
    sendPort.send([answer.sendPort, num1, num2]);
    return answer.first;
  }

  static void countEvent2(SendPort port) {
    final rPort = ReceivePort();
    port.send(rPort.sendPort);
    rPort.listen((message) {
      final send = message[0] as SendPort;
      final n1 = message[1] as int;
      final n2 = message[2] as int;
      send.send(countEven(n1, n2));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('$myCount'),
            MaterialButton(
              onPressed: test,
              child: Text('点击按钮'),
            ),
          ],
        ),
      ),
    );
  }
}

1、创建指定个数的isolate

Future<LoadBalancer> loadBalancer = LoadBalancer.create(2, IsolateRunner.spawn);

2、使用

int useLoadBalancer() async {
    final lb = await loadBalancer;
    int res = await lb.run<int, int>(_doSomething, 1);
    return res;
  }

每个isolate中执行顺序:
每次执行前先微任务队列判断有没有要处理,没有微任务再在event队列执行一个event任务,单个event任务处理完之后,再从头遍历微任务队列是否有新的微任务。


7776337-244d682635d9b2f3.png

微任务包括:

创建微任务:

scheduleMicrotask((){
      print("微任务2");
    });

Flutter 事件机制 - Future 和 MicroTask 全解析
flutter之-dart多线程isolate(二)

上一篇下一篇

猜你喜欢

热点阅读