0

I was wondering when exactly a Dart program terminates.

Take the following program:

import 'dart:isolate';

Future<void> calculateTheAnswer(SendPort port) async {
  await Future.delayed(Duration(seconds: 1));
  port.send(42);
}

void main() async {
  var port = ReceivePort()..listen(print);
  await Isolate.spawn(calculateTheAnswer, port.sendPort)
    ..addOnExitListener(port.sendPort, response: 100);
}

Here, main isolate spawns another isolate that just sends 42 after a second. After the answer is sent, the isolate terminates, causing the exit listener to fire. Indeed, the program outputs 42 and then outputs 100, so the isolate terminates.

But the Dart program still keeps running. Why's that?

Marcel
  • 8,831
  • 4
  • 39
  • 50

1 Answers1

2

A Dart program terminates when all its isolates have terminated.

An isolate is terminated if there are no more events in the event loop and there are no open ReceivePorts anymore. To achieve that, the Dart VM tracks all ReceivePorts that an isolate created. An extreme example is void main() => ReceivePort(), a program which does not terminate.

By closing the port in the main isolate at the end, the program indeed terminates:

void main() async {
  var port = ReceivePort()..listen(print);
  var exitPort = ReceivePort();
  exitPort.listen((_) {
    port.close();
    exitPort.close();
  });

  await Isolate.spawn(calculateTheAnswer, port.sendPort)
    ..addOnExitListener(exitPort.sendPort);
}
Marcel
  • 8,831
  • 4
  • 39
  • 50