从下面显示的简单隔离代码中可以预期到“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未连接到主隔离,它仅存在于生成的隔离中。
此代码在两个隔离中均执行
var mainReceivePort = new ReceivePort();
并且每个隔离都获得了一个不以任何方式未连接的
mainReceivePort
实例。在第二个示例中,连接到主要隔离对象的
sendPort
的mainReceivePort
被传递到生成的隔离对象,并且传递给它的消息将被连接的主要隔离对象的mainReceivePort
接收。
关于dart - 隔离代码未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45716994/