Created
March 1, 2020 07:40
-
-
Save Abdullamhd/6f7cea98b7a05c2689e33010398d423f to your computer and use it in GitHub Desktop.
isolate example in dart programming language
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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