首页 > 建站教程 > dart >  dart笔记22:Isolate使用案例正文

dart笔记22:Isolate使用案例

dart笔记22:Isolate使用案例,在dart里,所有的dart代码都运行在一个Isolate里,重新开个Isolate,相当于开个微进程,多个进程之间通过port发送和接收数据:
import 'dart:isolate';
import 'dart:io';

void main() {
  print('main isolate start');

  create_isolate();

  print('main isolate end');

  //执行结果:
  //main isolate start
  //main isolate end
  //main isolate listen:{type: port, data: SendPort}
  //main isolate listen:{type: message, data: new isolate finish}
  //new isolate listen:{type: message, data: main isolate message}
}

void create_isolate() async {
  SendPort sendPort;
  ReceivePort receivePort = ReceivePort();

  //告知new isolate,main isolate的接收端口是多少。
  Isolate newIsolate = await Isolate.spawn(doWork, receivePort.sendPort);

  //接受子线程的传回的内容
  receivePort.listen((message) {
    print('main isolate listen:$message');
    if (message['type'] == 'port') {
      sendPort = message['data'];
    } else {
      sendPort?.send({'type': 'message', 'data': 'main isolate message'});
    }
  });
}

void doWork(SendPort sendPort) {
  ReceivePort receivePort = ReceivePort();

  //接受主线程的传回的内容
  receivePort.listen((message) {
    print('new isolate listen:$message');
  });

  //发送数据
  sendPort.send({'type': 'port', 'data': receivePort.sendPort});

  //模拟发送
  sleep(Duration(seconds: 3));
  sendPort?.send({'type': 'message', 'data': 'new isolate finish'});
}