Dart Isolates As Workers

后端 未结 4 630
不思量自难忘°
不思量自难忘° 2021-02-09 20:35

Edited to make the question more clear.

I am trying to work with Isolates (or Web Workers) in Dart. The only ways I can find to communicate between the

4条回答
  •  日久生厌
    2021-02-09 20:48

    As of Dart 1.0, you can use isolates like this:

    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++}');
        });
      });
    }
    

提交回复
热议问题