Isolate线程通信 flutter

A、B互传消息

A、B都创建自己的 接收端口和发送端口

A将自己的发送端口发送给对面B,B才能拿到A的发送端口,给A发送消息

A监听自己的接收端口,拿到B发给自己的消息

B监听自己的接收端口,拿到A发给自己的消息

void function_main() async {
    print("当前线程:"+ Isolate.current.debugName);
    // 创建主线程ReceivePort对象用来监听回调的数据
    var receivePort = new ReceivePort();
    // 把主线程SendPort对象发送到子线程
    await Isolate.spawn(entryPoint, receivePort.sendPort);

    receivePort.listen((message) {
      SendPort sendPort = message;
      // 用子线程发送过来的SendPort对象-发送数据,-》子线程就会收到通知
      sendPort.send("回复给子线程的内容");
      // 关闭监听
      receivePort.close();
    });
  }
  void entryPoint(SendPort sendPort) async {
    // 创建子线程ReceivePort对象
    var port = new ReceivePort();
    // 把子线程SendPort对象发送到主线程
    sendPort.send(port.sendPort);
    // 这里是接收到 主线程给回复的内容
    await for (var data in port) {
      print("data $data");
    }
  }

 

 

https://www.jianshu.com/p/0f9250e92712

posted @ 2024-03-01 10:53  黄增松  阅读(32)  评论(0编辑  收藏  举报