Skip to content

Instantly share code, notes, and snippets.

@Abdullamhd
Created March 1, 2020 07:40
Show Gist options
  • Save Abdullamhd/6f7cea98b7a05c2689e33010398d423f to your computer and use it in GitHub Desktop.
Save Abdullamhd/6f7cea98b7a05c2689e33010398d423f to your computer and use it in GitHub Desktop.
isolate example in dart programming language
/// dart complete isolate example
import 'dart:io';
import 'dart:async';
import 'dart:isolate';
Isolate isolate;
void start() async {
ReceivePort receivePort= ReceivePort(); //port for this main isolate to receive messages.
isolate = await Isolate.spawn(runTimer, receivePort.sendPort);
receivePort.listen((data) {
stdout.write('RECEIVE: ' + data + ', \n');
});
}
void runTimer(SendPort sendPort) {
int counter = 0;
Timer.periodic(new Duration(seconds: 1), (Timer t) {
counter++;
String msg = 'notification ' + counter.toString();
stdout.write('SEND: ' + msg + ' - ');
sendPort.send(msg);
});
}
void stop() {
if (isolate != null) {
stdout.writeln('killing isolate');
isolate.kill(priority: Isolate.immediate);
isolate = null;
}
}
void main() async {
stdout.writeln('spawning isolate...');
await start();
stdout.writeln('press enter key to quit...');
await stdin.first;
stop();
stdout.writeln('goodbye!');
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment