Sub topic 10
Building a Long-Lived Worker Isolate
This chapter assumes basic Dart syntax, async/await, Future, and streams. It also assumes you understand that isolates do not share mutable memory. The examples use Dart 3 records and run on native Dart platforms.
Why use a long-lived worker?
Isolate.run is convenient for one job. It creates an isolate, runs a callback, returns the result, and then lets the isolate end. Creating an isolate has a cost, so repeating this process for many small jobs can be inefficient.
A long-lived worker stays alive and accepts several jobs through a SendPort. The calling isolate sends requests. The worker performs the work and sends responses back through another port.
A port is an endpoint for isolate messages:
ReceivePortreceives messages and exposes them as a stream.SendPortsends messages to a receive port.- The two isolates communicate by passing send ports to each other.
Starting the worker and exchanging ports
The worker needs a way to send its results back. The main isolate first creates a ReceivePort and passes its SendPort to the worker. The worker creates its own ReceivePort, then sends that port's SendPort back.
import 'dart:async';
import 'dart:isolate';
int _sumTo(int n) {
var sum = 0;
for (var i = 1; i <= n; i++) {
sum += i;
}
return sum;
}
void _worker(SendPort toMain) {
final commands = ReceivePort();
// Tell the main isolate where to send commands.
toMain.send(commands.sendPort);
commands.listen((message) {
if (message == null) {
commands.close();
return;
}
final (id, n) = message as (int, int);
final result = _sumTo(n);
// Include the request ID so the caller can match the response.
toMain.send((id, result));
});
}
Future<void> main() async {
final results = ReceivePort();
await Isolate.spawn(_worker, results.sendPort);
final events = StreamIterator<dynamic>(results);
// The first message is the worker's command port.
await events.moveNext();
final toWorker = events.current as SendPort;
toWorker.send((1, 100000000));
// The next message is the result for request 1.
await events.moveNext();
final (id, value) = events.current as (int, int);
print('job $id -> $value');
// Tell the worker to stop, then close the local receive port.
toWorker.send(null);
results.close();
}The worker function must be reachable by the new isolate. A top-level or static function is the clearest choice. The worker receives the main isolate's SendPort, creates a command port, and sends the command port back.
The request contains an ID and an input value. The response contains the same ID and the computed value. IDs matter when several jobs can be active at once. Without them, responses can be difficult to associate with their requests.
Managing a worker in real applications
A production worker usually wraps this setup in a class. The class can keep a map from request IDs to Completer objects. A Completer lets the class return a Future immediately and complete that future when the matching response arrives.
The worker protocol should define more than successful results. For example, use message envelopes such as these:
| Message | Purpose |
|---|---|
| `(id, input)` | Start a job |
| `(id, result, null)` | Report success |
| `(id, null, errorText)` | Report failure |
| `null` | Stop the worker |
Keep the protocol small and explicit. Validate incoming messages before casting them. A malformed message should produce a controlled error rather than terminate the worker unexpectedly.
Errors, queues, and shutdown
A worker's uncaught exception can terminate its isolate. For recoverable job failures, catch exceptions inside the worker and send an error response containing the request ID. The main isolate can then complete the matching future with an error.
A busy worker processes messages one at a time. Messages can accumulate in its receive queue, so callers may need a maximum queue size or a way to reject new work. If jobs are independent and expensive, several workers can process jobs in parallel. More workers also mean more memory and message traffic.
Use a long-lived worker when startup overhead matters or when many related jobs use the same worker state. Use Isolate.run for a small number of independent tasks. Do not use a worker merely to move trivial work away from the main isolate.
Exercise
Why does the example include a request ID in both the request and the response?
Show answer
The ID lets the main isolate match each response with the Future or operation that created the request, even when several jobs are in flight.