在桌面flutter应用程序(linux)的工作中,我需要在隔离中执行一些密集的计算任务。但是,虽然这个隔离正在执行这么长的操作,但它并没有读取传入的消息(这似乎是合乎逻辑的)。 我希望在它表演时仍然能够与它交流。
ReceivePort rPort;
SendPort sPort;
Isolate isolate;
void main() {
rPort = ReceivePort();
isolate = await Isolate.spawn(entryPoint, receivePort.sendPort);
sPort = await rPort.first;
sendMessage("perform"); // this is being processed
sendMessage("controlMessage"); // this is being processed after the perform has ended
}
void sendMessage(String msg) {
ReceivePort localReceivePort = ReceivePort();
sendPort.send([msg, localReceivePort.sendPort]);
}
void entryPoint(SendPort sendPort)
{
ReceivePort receivePort = ReceivePort();
sendPort.send(receivePort.sendPort);
receivePort.listen((message) {
String data = msg[0];
SendPort reply = msg[1];
print(data);
if(data == "perform") performBlockingOperation();
else if(data == "controlMessage") controlPerformance();
repy.send("something");
});
}
我尝试了很多选项:使 PerformBlockingOperation 异步,但这似乎不起作用。 即使尝试在隔离返回内创建 native 线程
../../third_party/dart/runtime/vm/runtime_entry.cc: 3331: error: Cannot invoke native callback outside an isolate.
有办法实现我正在尝试的目标吗?
最佳答案
使计算异步是正确的第一步。 第二步是在计算过程中的某些点实际放弃控制。
然后在计算代码中插入一些 await Future.delayed(Duration.zero);
语句,该语句会阻塞其他所有内容。计算不要太深入,因为它确实会引入延迟,但通常足以使您的隔离有机会偶尔检查新事件。
关于flutter - 如何与 Dart/Flutter 中执行阻塞操作的isolate进行通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61436422/