在dart:isolate"中有dart的`spawnUri(...)`的例子吗?

Fre*_*ind 3 dart dart-isolates

有一个spawnUri(uri)功能dart:isolate,但我找不到任何例子.我已经猜到了它的用法,但都失败了.

假设有2个文件,在第一个文件中,它将调用spawnUri第二个文件,并与之通信.

first.dart

import "dart:isolate";

main() {
  ReceivePort port = new ReceivePort();
  port.receive((msg, _) {
    print(msg);
    port.close();
  });
   var c = spawnUri("./second.dart");
   c.send(["Freewind", "enjoy dart"], port.toSendPort());
}
Run Code Online (Sandbox Code Playgroud)

second.dart

String hello(String who, String message) {
   return "Hello, $who, $message";
}

void isolateMain(ReceivePort port) {
  port.receive((msg, reply) => reply.send(hello(msg[0], msg[1]));
}

main() {}
Run Code Online (Sandbox Code Playgroud)

但是这个例子不起作用.我不知道什么是正确的代码,如何修复它?

Set*_*add 6

这是一个适用于Dart 1.0的简单示例.

app.dart:

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

main() {
  Element output = querySelector('output');

  SendPort sendPort;

  ReceivePort receivePort = new ReceivePort();
  receivePort.listen((msg) {
    if (sendPort == null) {
      sendPort = msg;
    } else {
      output.text += 'Received from isolate: $msg\n';
    }
  });

  String workerUri;

  // Yikes, this is a hack. But is there another way?
  if (identical(1, 1.0)) {
    // we're in dart2js!
    workerUri = 'worker.dart.js';
  } else {
    // we're in the VM!
    workerUri = 'worker.dart';
  }

  int counter = 0;

  Isolate.spawnUri(Uri.parse(workerUri), [], receivePort.sendPort).then((isolate) {
    print('isolate spawned');
    new Timer.periodic(const Duration(seconds: 1), (t) {
      sendPort.send('From app: ${counter++}');
    });
  });
}
Run Code Online (Sandbox Code Playgroud)

worker.dart:

import 'dart:isolate';

main(List<String> args, SendPort sendPort) {
  ReceivePort receivePort = new ReceivePort();
  sendPort.send(receivePort.sendPort);

  receivePort.listen((msg) {
    sendPort.send('ECHO: $msg');
  });
}
Run Code Online (Sandbox Code Playgroud)

建设分为两步:

  1. pub build
  2. dart2js -m web/worker.dart -obuild/worker.dart.js

请在此处查看完整项目:https://github.com/sethladd/dart_worker_isolates_dart2js_test


Ale*_*uin 3

警告:此代码已过时。

将secondary.dart替换为以下内容以使其正常工作:

import "dart:isolate";

String hello(String who, String message) {
  return "Hello, $who, $message";
}

main() {
  port.receive((msg, reply) => reply.send(hello(msg[0], msg[1])));
}
Run Code Online (Sandbox Code Playgroud)