如何在一个ReceivePort dart上进行多个订阅



我有一个创建N个隔离的任务,以及一个将传递给这些隔离的主ReceivePort,通过使用这个ReceivePort,我传递了函数所需的所有信息,以给我一个理想的输出。它第一次工作,然而,任何连续的消息发送给这些隔离,接收它们会抛出这样的错误

这是我的代码

//main receive port
var controlPort = ReceivePort();
...
class _MainScreenState extends State<MainScreen> {
final ImagePicker _picker = ImagePicker();
Future<ui.Image>? image;
@override
void initState() {
for (int i = 0; i < Platform.numberOfProcessors; i++) {
Future<Isolate> isolate =
Isolate.spawn(Core.readAndMapFast, controlPort.sendPort);
}
}
@override
Widget build(BuildContext context) {
...
static void readAndMapFast(SendPort sendPort) async {
//sending SendPort of a created isolate to the main thread
ReceivePort receivePort = ReceivePort();
sendPort.send(receivePort.sendPort);
receivePort.first.then((message) {
//listening for a message coming from main thread and populating it with all needed 
//data
message as Arguments;
Arguments arguments = Arguments(message.imgList, message.lutList,
message.imgHeight, message.imgWidth, message.widthLut, message.order);
//ecexuting all needed operations and after that sending message to the main thread
...
sendPort.send(output);
//in the main thread we are listening for messages from RecievePort we created at 
//the very beginning
await for (dynamic message in controlPort.asBroadcastStream()) {
if (message is SendPort) {
//waiting for a message from isolates and if its type is SendPort i.e isolate sending 
//its first message we are sending needed arguments to a function
message.send(args[i]);
} else {
message as FinalList;
counter++;
postEditList.add(message);
if (counter == numberOfWorkers) {
Stopwatch timerr = Stopwatch();
timerr.start();
for (int t = 0; t < postEditList.length; t++) {
FinalList list =
postEditList.where((element) => element.order == t).first;
bytesBuilder.add(list.imgSubList);
}
break;
}
}
}

我建议我必须使用ReceivePort(). asbroadcaststream(),但是我不能发送消息和用它做其他事情。因为在它变成流之后,我们没有SendPort。

我找到解决办法了。这很简单。我们有一个主ReceivePort,我们将使用它在隔离和主线程之间进行通信,并且我们还创建了一个BroadcastStream,它将用于侦听来自ReceivePort的任何更新。

var controlPort = ReceivePort();
var broadcastStream = controlPort.asBroadcastStream();

然后你所要做的就是通过

收听broadcastStream而不是controlPort的更新。
broadcastStream.listen((event) {});

我希望它能帮助到那些被同样的问题困住的人

相关内容

  • 没有找到相关文章

最新更新