Home > front end >  Correctly killing newly spawned isolates
Correctly killing newly spawned isolates

Time:12-07

I am aware of the fact that when both microtask and event queues of an isolate are empty, the isolate is killed. However, I'm not able to find a reference on the documentation of how a worker isolate can be killed under certain circumstances.


Context

Let's make this example:

Future<void> main() {
  final receivePort = ReceivePort();
  final worker = await Isolate.spawn<SendPort>((_) {}, receivePort.sendPort);

  await runMyProgram(receivePort, worker);
}

Here the main isolate is creating a new one (worker) and then the program starts doing stuff.


Question

How do I manually kill the newly spawned isolate when it's not needed anymore? I wasn't able to explicitly find this information on the documentation so I am kind of guessing. Do I have to do this?

 receivePort.close();
 worker.kill();

Or is it enough to just close the port, like this?

  receivePort.close();

Note

I thought about this. If the worker isolate has both queues (microtask and event) empty and I close the receive port, it should be killed automatically. If this is the case, calling receivePort.close() should be enough!

CodePudding user response:

If you want to make sure the child isolate shuts down, even if it's in the middle of doing something, you'll want to call Isolate.kill().

However, as you've already pointed out, an isolate will exit on its own if it has no more events to process and it holds no open ports (e.g., timers, open sockets, isolate ports, etc). For most cases, this is the ideal way to dispose of an isolate when it's no longer used since it eliminates the risk of killing the isolate while it's in the middle of doing something important.

Assuming your child isolate is good about cleaning up its own open ports when it's done doing what it needs to do, receivePort.close() should be enough for you to let it shut down.

  • Related