【问题标题】:Why doesn't the isolate receive the stop message?为什么隔离器没有收到停止消息?
【发布时间】: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 感谢您的帮助!从隔离到小部件的通信工作正常(回复端口(@98​​7654326@)通过onMessageReceivedFromIsolate() 传递)。从小部件向下发送到隔离时会出现问题:sendToIsolatePort.send() 似乎已执行(在小部件处),但未调用 onIsolateMessageReceived()(在隔离处)。换句话说:消息不会到达隔离区。相当复杂...
  • 我看到一个问题:您的while (isRunning) 将在我们的主隔离中消耗所有时间。因此没有时间可以调用您的onIsolateMessageReceived!尝试删除您的 while 循环,并改为:while(isRunning) await Future.delayed(Duration(seconds: 1));

标签: flutter dart dart-isolates


【解决方案1】:

(从上面的 cmets 改写,因为这是解决问题的答案。)

我看到一个问题:您的while (isRunning) 将在我们的主隔离中消耗所有时间。因此没有时间可以调用您的onIsolateMessageReceived!尝试删除您的 while 循环,并改为执行此操作:while(isRunning) await Future.delayed(Duration(seconds: 1));

至于执行线程:不,没有别的。隔离是颤振的基本构建块,这就是设计 - 没有共享内存。但是,确实存在一些小捷径。例如,看看: api.flutter.dev/flutter/foundation/compute.html ,这是在另一个“线程”(隔离)中进行计算的更简单方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2012-06-09
    • 1970-01-01
    • 2014-11-12
    • 1970-01-01
    • 2021-08-08
    • 2017-07-08
    相关资源
    最近更新 更多