Sub topic 9
Isolate.spawn and ports
This chapter assumes you are comfortable with async/await, Future, and basic Stream usage. You should also know that Isolate.run runs one closure in a new isolate and returns its result. Isolate.run is built on the lower-level pieces covered here: Isolate.spawn, ReceivePort, and SendPort. Once you can use them directly, you can build workers that live longer than one job, report errors, and shut down cleanly.
What Isolate.spawn does
Isolate.spawn creates a new isolate and calls an entry-point function in it. The signature, trimmed to the parts that matter:
Future<Isolate> spawn<T>(
void Function(T message) entryPoint,
T message, {
bool paused = false,
bool errorsAreFatal = true,
SendPort? onExit,
SendPort? onError,
String? debugName,
});The message argument is copied into the new isolate and passed to entryPoint. The new isolate has its own heap and its own event loop, so the entry point cannot see any variable from the spawning isolate. Whatever it needs must arrive through message.
The returned Future completes when the isolate has been created, not when it finishes its work. The Isolate object is a handle you can use to pause, resume, or kill the new isolate.
Use a top-level function or a static method as the entry point. A closure also compiles, but it can capture state you did not mean to copy (see the earlier chapter on closure capture).
Ports: the only channel
Isolates talk through two classes from dart:isolate:
- A
ReceivePortis the receiving end. It is aStream<dynamic>, so you canlistento it,awaititsfirstelement, or wrap it in aStreamIterator. - A
SendPortis the sending end. EachReceivePorthas one, available asreceivePort.sendPort. Callingsend(value)delivers a copy ofvalueto thatReceivePort.
A SendPort is itself sendable. That is how two isolates get connected. The parent creates a ReceivePort and passes its SendPort as the spawn message. The child can then send results back.
import 'dart:isolate';
void _hello(SendPort reply) {
reply.send('hello from ${Isolate.current.debugName}');
}
Future<void> main() async {
final port = ReceivePort();
await Isolate.spawn(_hello, port.sendPort, debugName: 'greeter');
final msg = await port.first;
print(msg);
port.close();
}Here port.first listens, takes one message, and cancels the subscription. The explicit close() is harmless and makes the intent clear.
Ports keep isolates alive
An isolate stays alive while it has pending work or an open ReceivePort that someone is listening to. The same applies to the main isolate of a Dart command-line program. If you forget to close a port, the program never exits. In Flutter the app keeps running regardless, but the port and its listener leak.
The handshake pattern
The spawn message goes only from parent to child. For a worker that should receive many requests, the child needs its own inbox, so the parent needs the child's SendPort. The standard solution is a handshake:
- The parent creates a
ReceivePortand passes itsSendPortto the child. - The child creates its own
ReceivePortand sends that port'sSendPortback through the first one. - The parent now holds a
SendPortfor the child, and the child holds one for the parent.
The following program implements that flow. Each request carries its own reply port, so the caller never has to match answers to questions by hand.
import 'dart:isolate';
void _echoWorker(SendPort toMain) {
final inbox = ReceivePort();
toMain.send(inbox.sendPort);
inbox.listen((message) {
final (String text, SendPort reply) = message as (String, SendPort);
reply.send(text.toUpperCase());
});
}
Future<void> main() async {
final handshake = ReceivePort();
final isolate = await Isolate.spawn(_echoWorker, handshake.sendPort);
final toWorker = await handshake.first as SendPort;
final reply = ReceivePort();
toWorker.send(('hello', reply.sendPort));
print(await reply.first); // HELLO
isolate.kill();
}The request is a record, (String, SendPort). Records of sendable values are sendable. The worker casts the dynamic message back to the expected shape in one pattern. If the shape is wrong, the cast throws inside the worker, which is why the error-reporting options below matter.
Per-request reply ports versus job IDs
Creating a ReceivePort for every request is simple and correct, and it costs little for occasional jobs. For thousands of small requests per second, one shared reply port and an integer ID on each message is cheaper, but you must keep a map from ID to pending Completer. Start with reply ports and switch only if profiling shows port creation matters.
Sending and copying
Every send copies the message into the receiving isolate's heap. Strings, numbers, lists, maps, sets, records, SendPort, and instances of your own classes can all be sent. Objects that wrap native resources cannot. Examples are a ReceivePort, a Socket, or anything created with dart:ffi pointers. Sending one throws an ArgumentError at the send call.
Copying has two consequences:
- The receiver gets an independent object. Changing it does not change the sender's original.
- Large messages cost time proportional to their size, on the sending side and again on the receiving side.
The next chapters cover ways to avoid large copies. One preview is Isolate.exit, which ends the current isolate and hands a message to a port without copying it:
import 'dart:isolate';
void _build(SendPort out) {
final big = List<int>.generate(1000000, (i) => i * 2);
Isolate.exit(out, big); // ownership moves; no copy
}
Future<void> main() async {
final port = ReceivePort();
await Isolate.spawn(_build, port.sendPort);
final list = await port.first as List<int>;
print(list.length);
}Isolate.run uses Isolate.exit internally to return its result. That is the reason one-off jobs do not pay for copying a large result.
Watching for errors and exit
By default an uncaught error in the spawned isolate terminates that isolate (errorsAreFatal is true), and the parent hears nothing. That is a silent failure. Pass onError and onExit ports to observe both:
import 'dart:isolate';
void _risky(SendPort out) {
out.send('starting');
throw StateError('boom');
}
Future<void> main() async {
final messages = ReceivePort();
final errors = ReceivePort();
final exits = ReceivePort();
await Isolate.spawn(
_risky,
messages.sendPort,
onError: errors.sendPort,
onExit: exits.sendPort,
);
messages.listen((m) => print('message: $m'));
errors.listen((e) {
final report = e as List<dynamic>;
print('error: ${report[0]}');
print('stack: ${report[1]}');
});
await exits.first;
messages.close();
errors.close();
}An error arrives on the onError port as a two-element list. The first element is the error's toString() and the second is the stack trace as a string, or null. The original exception object is not delivered, so you cannot catch it by type the way you can with Isolate.run. The onExit port receives a null message when the isolate ends, for any reason. Awaiting it is a reliable way to know the worker is gone.
If you set errorsAreFatal: false, the isolate survives uncaught errors and continues handling events. This suits a worker that processes independent jobs, but it can leave the isolate's state half-updated after a failure. Prefer catching errors inside the message handler and sending a failure message back.
Controlling the isolate
The Isolate handle gives you three controls.
| Method | Effect | Note |
|---|---|---|
| `kill()` | Ends the isolate. | Default is `Isolate.beforeNextEvent`, so the isolate stops before running its next event. Use `Isolate.immediate` to stop sooner. |
| `pause()` / `resume()` | Stops and restarts event handling. | `resume` needs a capability, such as `isolate.pauseCapability`. |
| `addOnExitListener(port)` | Sends a message when the isolate exits. | Same effect as the `onExit` argument to `spawn`. |
Spawning with paused: true starts the isolate suspended. This lets you attach listeners before any code runs. Then call isolate.resume(isolate.pauseCapability!).
Killing an isolate does not run finally blocks or close its ports in an orderly way. If the worker holds files or sockets, tell it to shut down by message, let it clean up, and have it call Isolate.exit, as the long-lived worker chapter shows.
Common mistakes
- Sending an unsendable object. A
ReceivePort, a socket, or a closure over one fails atsendtime with anArgumentError. Send the data or aSendPortinstead. - Reading
firsttwice.ReceivePortis a single-subscription stream.await port.firstfollowed byawait port.firstthrows, because the first call closed it. Use aStreamIteratoror onelistencall to read several messages. - Expecting shared state. A top-level variable set in the parent is not set in the child. Each isolate gets its own copy of top-level state, initialized fresh.
- Casting without checking.
message as (int, int)throws aTypeErrorin the worker if the sender used a different shape. Define one request type and use it on both sides. - Using spawn on Flutter web.
dart:isolateis not available when compiling to JavaScript, so this code will not build for the web. The platform-limits chapter covers the alternatives.
Exercise
A parent spawns a worker and passes port.sendPort as the spawn message. The worker crashes with an uncaught exception, and the parent's await port.first never completes. Why, and what two arguments to Isolate.spawn would let the parent notice and react?
Show answer
With the default errorsAreFatal: true, the isolate is terminated by the uncaught error, and nothing is sent to port, so first waits forever. Passing onError (a SendPort that receives [errorString, stackTraceString]) and onExit (a SendPort that receives null when the isolate ends) lets the parent learn about the crash. It can then complete or fail its own pending work.
Exercise
Write the entry point and the parent code for a worker that receives an int through the handshake pattern, replies with its square on a per-request reply port, and is killed afterward. Which values travel through which port?
Show answer
The parent passes handshake.sendPort at spawn. The worker creates inbox, then sends inbox.sendPort through the handshake port. The parent reads it with await handshake.first as SendPort. The parent then creates reply = ReceivePort() and sends (5, reply.sendPort). The worker listens on inbox, casts to (int, SendPort), and calls reply.send(n * n). The parent awaits reply.first (25) and then calls isolate.kill(). The SendPort values travel through the handshake port and the request, and the number travels through the reply port.