Flutter学习笔记-Dart的跨线程异步操作Isolate

146 阅读1分钟

Flutter学习笔记-Dart的跨线程异步操作Isolate

Dart在单线程模式中增加了Isolate提供跨线程的真异步操作。因为在Dart中线程不会共享内存,所以也不存在死锁,从而导致了Isolate之间的数据只能通过port的端口方式发送接口。所以Isolate也称为隔离的执行。

Isolate主要在dart:isolate包中,其中:

  • Isolate用于Dart执行上下文隔离;
  • ReceivePort与SendPort一起,是唯一的通信方式;
  • SendPort将消息发送到其他ReceivePort;

示例代码:

class _MyHomePageState extends State<MyHomePage> {
  Isolate isolate;
  // 利用ReceivePort监听和发送数据
  ReceivePort receivePort=ReceivePort();
  String mes="";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    resignIsolate();
  }

  resignIsolate()async{
    // 利用spawn快速创建Ioslate
    isolate=await Isolate.spawn(_incrementCounter, receivePort.sendPort);
    isolate=await Isolate.spawn(_sendTest, receivePort.sendPort);
    // 监听接受到的数据
    receivePort.listen((message) {
      setState(() {
        mes+="\n$message";
      });
    });
  }

  // 发送数据
  static _incrementCounter(SendPort port) {
    port.send("demo");
  }

  static _sendTest(SendPort port){
    port.send("test");
  }

  @override
  void dispose() {
    // TODO: implement dispose
    // 销毁Isolate
    isolate?.kill(priority: Isolate.immediate);
    isolate=null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              mes,
            ),
            TextButton(onPressed: (){
              _sendTest(receivePort.sendPort);
            }, child: Text("测试发送"))
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: (){
          _incrementCounter(receivePort.sendPort);
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

此段代码利用spawn建立了两个Ioslate,通过统一的ReceivePort进行接收和发送数据。

代码效果: image.png