Danny Tuppeny Danny Tuppeny - 3 months ago 8
Dart Question

Why does this dart program hang for 5 seconds after the last line of main()?

When I run this code, it outputs

starting...
, the HTTP repsonse body and then
finished
but then seems to wait for approx 5 seconds before the Dart process terminates.

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");
}


Why? What's happening after the last
print()
that takes so long to end?

Answer

The HttpClient also needs closing:

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()); // <-- ####################
}
Comments