Dart program not exiting

Issue

I’m having trouble tracking down why my dart program isn’t terminating. I’m pretty sure it’s something to do with either isolates, or stream controllers, and making sure they are closed, but I can’t work out what the problem is.

On all of my StreamControllers i’m calling await streamControllerName.close();, but I think there is an isolate closing mechanism that I don’t know about. Would there be any reason why the event loop isn’t finishing and so the program isn’t exiting? Difficult to give more details as the code is quite long.

Solution

Dart programs stops when the main isolate has nothing left to do (so no code is executing and no events on the event or microtask queues) and nothing is subscribed to which can spawn events into the main isolate.

Besides Timer which can spawn delayed events, we have ReceivePort which allow us to send events into an isolate from another isolate. It should be noted that Dart does not keep track of the relationship between a ReceivePort and SendPort instances pointing to that ReceivePort.

This means that Dart does not know when a ReceivePort is no longer "in use" and it is therefore up to the developer to ensure closing any open ReceivePort by calling the close() method on each instance (notice that SendPort does not have any close() method) when they are no longer in use.

As long as there are any open ReceivePort in the main isolate, the program will continue running since an event might be spawned from one of these ReceivePort instances.

Answered By – julemand101

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.