【问题标题】:Bidirectional communication with isolates in Dart 2Dart 2 中与隔离物的双向通信
【发布时间】:2019-02-15 00:17:22
【问题描述】:

我正在尝试隔离,我想知道如何让其中一些进行繁重的计算,当根隔离询问他们当前的计算值时,他们会“按需”响应。

据我所知,唯一可以用作新创建的隔离消息的对象是 SendPort,这意味着只有生成的隔离可以与根隔离。我尝试发送一个 元组,但由于 ReceivePort 不是 SendPort,它被认为是非法的。

简而言之:

root good

root 隔离如何?

【问题讨论】:

标签: dart dart-isolates dart-2


【解决方案1】:

package:stream_channelIsolateChannel

这应该为您尝试做的事情提供很多帮助。

【讨论】:

    【解决方案2】:

    Guntercomment 我做了这个:

    import 'dart:async';
    import 'dart:io';
    import 'dart:isolate';
    
    Stopwatch stopwatch = new Stopwatch();
    
    main(args) async {
      ReceivePort rPort = new ReceivePort();
      rPort.listen((data) {
        print("<root> $data received");
        if (data is List) {
          String action = data[0];
          if (action == "register") {
            (data[1] as SendPort).send(stopwatch.elapsedMilliseconds);
          }
        }
      });
      stopwatch.start();
      await Isolate.spawn(elIsolate, rPort.sendPort);
      print("isolate spawned in ${stopwatch.elapsedMilliseconds} msecs"); //isolate spawned in 377 msecs
    }
    
    void elIsolate(SendPort sPort) {
      ReceivePort rPort = new ReceivePort();
      rPort.listen((data) {
        print("<Isolate> '$data' received"); //<Isolate> '387' received
      });
      sPort.send(["register", rPort.sendPort]);
    }
    

    而使用Kevinanswer 代码简化为:

    import 'dart:async';
    import 'dart:io';
    import 'dart:isolate';
    import 'package:stream_channel/stream_channel.dart';
    
    Stopwatch stopwatch = new Stopwatch();
    
    main(args) async {
      ReceivePort rPort = new ReceivePort();
      IsolateChannel channel = new IsolateChannel.connectReceive(rPort);
      channel.stream.listen((data) {
        print("<root> '$data' received at ${stopwatch.elapsedMilliseconds} msecs"); //<root> 'hello world' received at 1141 msecs
        channel.sink.add(stopwatch.elapsedMilliseconds);
      });
      stopwatch.start();
      await Isolate.spawn(elIsolate, rPort.sendPort);
      print("isolate spawned in ${stopwatch.elapsedMilliseconds} msecs"); //isolate spawned in 1111 msecs
    }
    
    void elIsolate(SendPort sPort) {
      IsolateChannel channel = new IsolateChannel.connectSend(sPort);
      channel.stream.listen((data) {
        print("<Isolate> '$data' received");
      });
      channel.sink.add("hello world");
    }
    

    【讨论】:

      猜你喜欢
      • 2012-10-07
      • 2020-08-24
      • 1970-01-01
      • 2020-06-29
      • 1970-01-01
      • 1970-01-01
      • 2016-06-06
      • 2018-10-04
      • 1970-01-01
      相关资源
      最近更新 更多