面试题答案
一键面试- 创建Isolate:
- 首先,定义一个顶级函数(不能是类的成员函数,因为Isolate运行在独立的内存空间,类成员函数的上下文无法直接在新Isolate中访问)作为新Isolate的入口点。例如:
void isolateEntryPoint(SendPort sendPort) { // 这里是新Isolate的执行代码 }
- 在主Isolate(通常是应用程序的主线程)中,使用
Isolate.spawn
方法创建新的Isolate:
SendPort mainSendPort; Isolate.spawn(isolateEntryPoint, mainSendPort).then((isolate) { // 可以在这里对新创建的Isolate进行管理,比如在不需要时关闭它 });
- 传递数据:
- 利用
SendPort
来传递数据。SendPort
是一个用于向另一个Isolate发送消息的对象。 - 在主Isolate中创建
SendPort
对象,并将其传递给新Isolate作为参数。例如:
SendPort mainSendPort = RawReceivePort().sendPort; Isolate.spawn(isolateEntryPoint, mainSendPort).then((isolate) { // 传递数据 mainSendPort.send('Hello from main isolate'); });
- 在新Isolate中,通过接收到的
SendPort
来接收数据,例如:
void isolateEntryPoint(SendPort sendPort) { RawReceivePort receivePort = RawReceivePort(); receivePort.listen((message) { // 处理接收到的消息 print('Received in isolate: $message'); }); sendPort.send(receivePort.sendPort); }
- 利用
- 接收结果:
- 新Isolate处理完任务后,通过
SendPort
将结果发送回主Isolate。 - 在主Isolate中,通过之前创建的
RawReceivePort
来监听结果。例如:
SendPort mainSendPort = RawReceivePort().sendPort; RawReceivePort receivePort = RawReceivePort(); receivePort.listen((result) { print('Received result in main isolate: $result'); }); Isolate.spawn(isolateEntryPoint, mainSendPort).then((isolate) { mainSendPort.send('Hello from main isolate'); });
- 在新Isolate中,处理完数据后发送结果:
void isolateEntryPoint(SendPort sendPort) { RawReceivePort receivePort = RawReceivePort(); receivePort.listen((message) { // 处理接收到的消息 var result = 'Processed: $message'; sendPort.send(result); }); sendPort.send(receivePort.sendPort); }
- 新Isolate处理完任务后,通过