Spawning isolates in Dart

Spawning new isolates in Dart is easy if you know how to do it:

main.dart

[dart]import ‚dart:isolate‘;
import ‚dart:async‘;

void main() {
Future isolate1 = Isolate.spawnUri(Uri.parse(‚isolate.dart‘), [], null);
Future isolate2 = Isolate.spawnUri(Uri.parse(‚isolate.dart‘), [], null);
Future.wait([isolate1,isolate2]);
while(true);
}[/dart]

Future.wait only waits until the two isolates are spawned. If the main application stops running, the two spawned isolates will stop running as well. That’s why we need a while(true)-loop here.

The isolate itself looks like this:

[dart]library isolate;

void main() {
print(‚isolate.main()‘);
while(true);
}[/dart]

The two arguments after the URI are used for a list of arguments and an optional message. If you want to use this, just modify the main method of your isolate:

[dart]
void main(args) {…}
void main(args, message) {…}[/dart]

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.