编辑以使问题更清楚。
我正在尝试在 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/