如何从隔离中获得简单答案?

时间:2019-07-11 14:47:12

标签: dart dart-isolates

我正在了解Isolate。我读了文档。并想写最少的工作示例。这是我的代码:

p[m][n]

这几乎可以,但是我不明白如何发送回简单的“ Hello”消息。我看了几个例子,发现中间件像main() async { ReceivePort receivePort = ReceivePort(); Isolate.spawn(echo, receivePort.sendPort); var sendPort = await receivePort.first; } echo(SendPort sendPort) { ReceivePort receivePort = ReceivePort(); sendPort.send(receivePort); } 。我对:

sendReceive()

var sendPort = await receivePort.first; 将存储生成的函数的名称/地址,我需要sendPort吗?

1 个答案:

答案 0 :(得分:0)

您已经说明了如何使用SendPort.send发送简单数据。实际上,您只能 发送原始数据类型,即文档中所述的null, num, bool, double, String
我将在下面完成您的示例。

import 'dart:isolate';

main() async {
  final receivePort = ReceivePort();
  await Isolate.spawn(echo, receivePort.sendPort);

  final Stream receivePortStream = receivePort.asBroadcastStream();

  receivePortStream.listen((message) {
    if (message is String) {
      print('Message from listener: $message');
    } else if (message is num) {
      print('Computation result: $message');
    }
  });

  final firstMessage = await receivePortStream.first;
  print(firstMessage);
}

echo(SendPort sendPort) {
  sendPort.send('hello');

  sendPort.send('another one');

  final computationResult = 27 * 939;
  sendPort.send(computationResult);
}

请注意,您只想发送'hello'而不发送其他ReceivePort,因为它不是原始值,因此甚至无法正常工作。
在我的示例中,我还设置了另一个侦听器,该侦听器将处理更多消息。

此外,我需要创建receivePortStream变量作为广播流,以便能够收听到它。如果您尝试在同一ReceivePort.listen上运行ReceivePort.firstReceivePort,则会出现异常。