【发布时间】:2021-01-15 14:25:36
【问题描述】:
UI 显示两个按钮:一个按钮用于启动隔离,第二个按钮用于在下一次停止它。 UI(小部件)代码如下所示:
SendPort sendToIsolatePort;
void _onStartIsolateButtonPushed() async {
ReceivePort receivePort = ReceivePort();
receivePort.listen(onMessageReceivedFromIsolate);
Isolate.spawn(runAsIsolate, receivePort.sendPort);
}
void _onStopIsolateButtonPushed() async {
sendToIsolatePort.send("Stop");
}
void onMessageReceivedFromIsolate(var message) {
if (message is String) {
print("Message received from isolate: " + message);
} else if (message is SendPort) {
print("Reply port received");
sendToIsolatePort = message;
sendToIsolatePort.send("Hello World?!?");
}
}
isolate.dart 中的代码如下所示: (注意:这个不在小部件或类中,只是一些全局函数)
import 'dart:isolate';
SendPort sendPort;
bool isRunning;
void runAsIsolate(SendPort port) async {
sendPort = port;
ReceivePort receivePort = ReceivePort();
receivePort.listen(onIsolateMessageReceived);
isRunning = true;
sendPort.send(receivePort.sendPort);
while (isRunning) {
_doSomething();
_doSomethingMore();
}
receivePort.close();
sendPort.send("Stopped");
print("Leaving isolate...");
}
void onIsolateMessageReceived(var message) {
if (message is String) {
print("Isolate: messate received: " + message);
if (message == "Stop") {
isRunning = false;
}
} else {
print("WTFlutter... " + message.toString());
}
}
void _doSomething() {}
void _doSomethingMore() {}
现在,由于某种原因,isolate 没有收到“Hello World?!?”也不是“停止”消息。你有什么想法为什么?以及如何解决?
另外:有没有更简单(或更短)的方式在颤振中执行线程?隔离方法,以及它的流式通信,对于像并行执行这样常见的事情来说似乎过于复杂了。
非常感谢您的建议。谢谢。
【问题讨论】:
-
至于执行线程:不,没有别的。隔离是颤振的基本构建块,这就是设计 - 没有共享内存。
-
尝试在
onMessageReceivedFromIsolate中添加else子句并打印一些内容以进行调试 -
看看:api.flutter.dev/flutter/foundation/compute.html,这是在另一个“线程”(隔离)中进行计算的更简单方法
-
@ch271828n 感谢您的帮助!从隔离到小部件的通信工作正常(回复端口(@987654326@)通过
onMessageReceivedFromIsolate()传递)。从小部件向下发送到隔离时会出现问题:sendToIsolatePort.send()似乎已执行(在小部件处),但未调用onIsolateMessageReceived()(在隔离处)。换句话说:消息不会到达隔离区。相当复杂... -
我看到一个问题:您的
while (isRunning)将在我们的主隔离中消耗所有时间。因此没有时间可以调用您的onIsolateMessageReceived!尝试删除您的 while 循环,并改为:while(isRunning) await Future.delayed(Duration(seconds: 1));
标签: flutter dart dart-isolates