隔离代码没有按预期工作

Isolate code didn't work as expected

预期 "Hello world" 来自如下所示的简单隔离代码,但没有奏效。

import 'dart:async';
import 'dart:isolate';

var mainReceivePort = new ReceivePort();

main() async {
  await Isolate.spawn(hello, null);
  await for (var msg in mainReceivePort) {  
    print(msg);
    return;
  }
}

hello(_) async {
  var sendPort = mainReceivePort.sendPort;
  sendPort.send("Hello world");
}

对代码进行以下更改后,它会按预期工作

import 'dart:async';
import 'dart:isolate';

var mainReceivePort = new ReceivePort();

main() async {
  await Isolate.spawn(hello, mainReceivePort.sendPort);
  await for (var msg in mainReceivePort) {  
    print(msg);
    return;
  }
}

hello(sendPort) async {
  sendPort.send("Hello world");
}

寻找线索。有什么想法吗?

在第一个示例中,sendPort 未连接到主隔离区,它仅存在于派生隔离区中。

此代码在两个 isolate 中执行

var mainReceivePort = new ReceivePort();

并且每个 isolate 都有一个不同的 mainReceivePort 实例,它们没有以任何方式连接。

在第二个示例中,连接到主隔离的 mainReceivePortsendPort 被传递给生成的隔离,传递给它的消息将被连接的 mainReceivePort 接收主要隔离。