为什么这个飞镖程序在main()的最后一行之后挂了5秒?

时间:2016-08-13 10:20:47

标签: dart

当我运行此代码时,它会输出starting...,HTTP repsonse主体,然后finished,但在Dart进程终止之前似乎等待约5秒。

import 'dart:io';
import 'dart:async';
import 'dart:convert';

Future<String> _sendRequest() async {
  var http = new HttpClient();
  return http
      .postUrl(Uri.parse("https://www.google.com/404"))
      .then((HttpClientRequest request) => request.close())
      .then((HttpClientResponse response) {
    return response.transform(UTF8.decoder).join("");
  });
}

main(List<String> args) async {
  print("starting...");
  print(await _sendRequest());
  print("finished");
}

为什么呢?在过去需要很长时间才能结束的print()之后发生了什么?

1 个答案:

答案 0 :(得分:1)

HttpClient还需要关闭:

Future<String> _sendRequest() async {
  var http = new HttpClient();
  return http
      .postUrl(Uri.parse("https://www.google.com/404"))
      .then((HttpClientRequest request) => request.close())
      .then((HttpClientResponse response) {
    return response.transform(UTF8.decoder).join("");
  }).whenComplete(() => http.close()); // <-- ####################
}