【问题标题】:Isolate code didn't work as expected隔离代码未按预期工作
【发布时间】:2017-08-16 14:58:21
【问题描述】:

从下面显示的简单隔离代码中预期的“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");
}

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

【问题讨论】:

  • “没用”到底是什么意思?预期的行为是什么?实际行为是什么?
  • 你为什么期望第一个例子,你通过null而不是mainReceivePort.sendPort,来工作?

标签: dart dart-isolates


【解决方案1】:

在第一个示例中,sendPort 没有连接到主隔离区,它仅存在于生成的隔离区中。

这段代码在两个isolate中执行

var mainReceivePort = new ReceivePort();

每个隔离区都有一个不同的mainReceivePort 实例,它们没有以任何方式连接。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 1970-01-01
    • 2016-07-06
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多