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 @   黄增松  阅读(63)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
点击右上角即可分享
微信分享提示