【问题标题】:two isolate send message by the port will drop some messges of dart 2.5 version两个隔离的端口发送消息会丢弃一些dart 2.5版本的消息
【发布时间】:2020-04-09 16:10:18
【问题描述】:

如果我从一个隔离区向主隔离区发送消息,则主隔离区无法接收完整消息。 我的测试代码被炸了:

import 'package:flutter/material.dart';
import 'dart:isolate';
import 'dart:async';

void main() {
  init();
  runApp(MyApp());
}

void test(SendPort port) {
  var cnt = 1;
  Timer.periodic(new Duration(microseconds: 10), (Timer timer){
    port.send(cnt++);
  });
}

void init() {
  ReceivePort port = new ReceivePort();
  print("create an isoalte...");
  Isolate.spawn(test, port.sendPort);
  port.listen((msg){
    print("the return is: $msg");
  });
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(

        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

如果我每秒发送消息就可以了,所以频率会影响主隔离接收消息,如果主隔离忙,它会丢弃消息吗? 端口是否使用消息队列相互通信?是同步还是异步?

【问题讨论】:

    标签: flutter dart dart-isolates


    【解决方案1】:

    端口通信使用消息队列,异步接收事件。如果正在运行的代码没有返回到事件循环,则隔离将不会处理任何传入的消息。它仍应接收所有消息并缓冲它们,直到有时间调用处理程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多