spawn static method
创建并启动一个新的isolate线程
name 该isolate的标识名,作为管理和查找用
entryPoint isolate入口函数,格式void Function(List<dynamic>)
message 可选,传递给isolate的初始消息(任意类型)
返回结果: Future<void> 表示异步处理完成
示例:
await IsolateTask.spawn('calc', myEntryPoint, 123);
Implementation
static Future<void> spawn(
String name,
void Function(List<dynamic>) entryPoint, [
dynamic message,
]) async {
if (_isolates.containsKey(name)) {
throw Exception('Isolate "$name" 已存在,请先kill后再spawn');
}
final receivePort = ReceivePort();
_receivePorts[name] = receivePort;
final isolate = await Isolate.spawn(
entryPoint,
[receivePort.sendPort, message],
);
_isolates[name] = isolate;
// 可自定义监听逻辑,用于处理子isolate返回主isolate的数据
receivePort.listen((msg) {
// TODO: 可以在此处理isolate的返回消息,如EventBus发送/回调等
});
}