Isolate

1、(Isolate)隔离的定义:类似于线程(区别就是Isolate数据不能通用,只能把数据传回主Isolate,再做其他处理,)
2、(Isolate)使用场景:用于做复杂的逻辑操作,时间超过500ms使用Isolate,没有超过使用Future,
3、(Isolate)注意点:Isolate不能直连channel,需要把数据传回主Isolate之后,再使用channel
4、Isolate.run用于一次性,Isolate.spawn用于多次
5、测试页面(Isolate.spawn)

class IsolateTestPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return IsolateTestPageState();
  }
}

class IsolateTestPageState extends State<IsolateTestPage> {
  var content = "点击计算按钮,开始计算";

  Timer timer;
  int v = 1;

  @override
  void initState() {
    super.initState();
    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        v++;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Isolate"),
      ),
      body: SafeArea(
        child: Center(
          child: Column(
            children: <Widget>[
              Container(
                  width: double.infinity, height: 500, child: Text(content)),
              TextButton(
                child: Text('计算${v}'),
                onPressed: () {
                  //卡死
                  // int result = sum(100000000000);
                  // content = "总和$result";
                  // setState(() {});

                  calculation(1000000000,(v){
                    print("计算结束--$v");
                    content = "总和$v";
                    setState(() {});
                  });
                },
              )
            ],
          ),
        ),
      ),
    );
  }



  calculation(int n, Function(String result) success) async {
    //创建一个ReceivePort
    final receivePort1 = new ReceivePort();
    //创建isolate
    Isolate isolate = await Isolate.spawn(createIsolate, receivePort1.sendPort);
    receivePort1.listen((message) {
      if (message is SendPort) {
        SendPort sendPort2 = message;
        sendPort2.send(n);
      } else {
        print(message);
        success(message);
        isolate.kill();
      }
    });
  }
  //创建isolate必须要的参数
  static void createIsolate(SendPort sendPort1) {
    final receivePort2 = new ReceivePort();
    //绑定
    print("收到信息");
    sendPort1.send(receivePort2.sendPort);
    //监听
    receivePort2.listen((message) async{
      //获取数据并解析
      print("计算中--$message");
      // await Future.delayed(Duration(seconds: 2),(){});
      // String ss = await Request.post<String>(
      //     "us/advert/public/getScreenAdvert",
      //     isToast: false);
      int n = message;
      String ss = '${sum(n)}';
      sendPort1.send(ss);
    });
  }

//计算0到 num 数值的总和
  static int sum(int num) {
    int count = 0;
    while (num > 0) {
      count = count + num;
      num--;
    }
    return count;
  }
}

6、测试二(Isolate.run)

  void _incrementCounter() async{
    print('value0:');
    int v = await test2();
    print('value1: ${v}');
  }

Future<int> test2()async{
  int taskres = await Isolate.run((){
      sleep(Duration(seconds: 2));
      return 3;
  });
  return taskres;
  // print('value2: ${taskres}');
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容