为什么 isolate 没有收到停止消息?

Why doesn't the isolate receive the stop message?

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 中的代码如下所示: (注意:这个不在小部件或 class 中,只是一些全局函数)

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() {}

现在,由于某种原因,隔离器既没有收到“Hello World?!?”也不是“停止”消息。你知道为什么吗?以及如何修复它?

另外:是否有更简单(或更短)的方法来执行 flutter 中的线程?隔离方法及其流通信对于像并行执行这样常见的事情来说显得过于复杂。

非常感谢您的建议。谢谢。

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

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

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