communication - Dart 作为 worker 隔离

标签 communication dart dart-isolates

编辑以使问题更清楚。

我正在尝试在 Dart 中使用 Isolates(或 Web Workers)。我能找到的在主线程和隔离线程之间进行通信的唯一方法是从主线程发送和调用 & 然后。但这是主线程向隔离传递一些数据的好方法。

如果我希望孤立者成为产生信息的人怎么办?就像一个游戏引擎在一个 worker 中完成所有的物理,然后将更新的世界信息发送到主线程?在 JavaScript 中,您可以随时发送数据。 Dart有没有有效的方法?还是我还要等主线程调用我再传给它?

附言我想知道,是否调用 & 然后阻塞线程直到回复完成?

最佳答案

从 Dart 1.0 开始,您可以像这样使用隔离:

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

void doStuff(SendPort sendPort) {
  print('hi from inside isolate');
  ReceivePort receivePort = new ReceivePort();
  sendPort.send(receivePort.sendPort);

  receivePort.listen((msg) {
    print('Received in isolate: [$msg]');
    sendPort.send('ECHO: $msg');
  });

}

void main() {
  SendPort sendPort;

  ReceivePort receive = new ReceivePort();
  receive.listen((msg) {
    if (sendPort == null) {
      sendPort = msg;
    } else {
      print('From isolate: $msg');
    }
  });

  int counter = 0;

  Isolate.spawn(doStuff, receive.sendPort).then((isolate) {
    new Timer.periodic(const Duration(seconds:1), (t) {
      sendPort.send('Count is ${counter++}');
    });
  });
}

关于communication - Dart 作为 worker 隔离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10302283/

相关文章:

dart - 无法暂停 Dart 隔离

java - nio上下文中的请求-响应同步/匹配

android - 如何在应用程序中与 2 个机器人进行通信?

visual-studio-code - 使用 12 GB 内存运行 Dart

firebase - flutter Isolate 中的共享偏好

flutter - Isolate 的入口点函数不能标记为异步

algorithm - 如果我采用 max(abs(m) 或 max(m),有什么区别?

android - 如何从广播中执行正在运行的服务的方法?

android - flutter :导航问题

flutter - Flutter Flat Button在其可见边框之外可以单击