Dart程序退出而不执行最后一条语句 [英] Dart program exits without executing last statement

查看:42
本文介绍了Dart程序退出而不执行最后一条语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解Streams并编写了一些代码.一切似乎都正常,程序以状态代码0退出.但是它不会打印循环完成"和主要完成"字符串.我不知道为什么.

I'm trying to understand Streams and wrote some code. Everything seems to work, the program exits with status code 0. But it doesn't print the 'loop done' and 'main done' strings. I can't figure out why.

import 'dart:async';

Stream<int> countStream(int to) async* {
      for (int i = 1; i <= to; i++) {
              yield i;
      }
}

class Retry {
    StreamController<int> _outgoing;

    Retry(Stream<int> incoming) {
        _outgoing = StreamController<int>();
        _outgoing.addStream(incoming);
    }

    Future<void> process() async {
        await for (final i in _outgoing.stream) {
            print("got $i");
        }
        print('loop done'); // Not printed
    }
}

void main() async {
  var stream = countStream(4);
  var retry = Retry(stream);
  await retry.process();
  print('main done'); // Not printed
}

推荐答案

_outgoing.stream 永远不会关闭,因此 waiting 之后的代码将永远不会执行.VM确实注意到该流上也不会有任何 new 事件,因此不会发生其他任何事情,并且可以退出.您可以通过以下方式修复该错误:

The _outgoing.stream is never closed, so code after the await for will never execute. The VM does notice that there also won't be any new events on that stream so nothing else will ever happen, and it can exit. You could fix the bug with:

_outgoing.addStream(incoming).whenComplete(() {
    _outgoing.close();
});

这篇关于Dart程序退出而不执行最后一条语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆