Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'dart:async';
- import 'dart:io';
- import 'dart:isolate';
- class FileRecorder {
- late String _filePath;
- late SendPort _sendPort;
- late ReceivePort _receivePort;
- late Isolate _isolate;
- final Completer<void> _isolateReady = Completer.sync();
- Future<void> start(String filePath) async {
- _filePath = filePath;
- _receivePort = ReceivePort();
- _receivePort.listen(_handleResponsesFromIsolate);
- _isolate = await Isolate.spawn(_startRemoteIsolate, _receivePort.sendPort);
- }
- Future<void> record(List<int> message) async {
- await _isolateReady.future;
- _sendPort.send(message);
- }
- Future<void> stop() async {
- await _isolateReady.future;
- _sendPort.send(true);
- }
- void _handleResponsesFromIsolate(dynamic message) {
- if (message is SendPort) {
- _sendPort = message;
- _isolateReady.complete();
- } else if (message is bool) {
- if (message == true) {
- _receivePort.close();
- _isolate.kill(priority: Isolate.immediate);
- }
- } else if (message is List<int>) {
- final contents = '${message.join(',')},';
- File file = File(_filePath);
- file.writeAsStringSync(contents, mode: FileMode.append);
- }
- }
- static void _startRemoteIsolate(SendPort port) {
- final receivePort = ReceivePort();
- port.send(receivePort.sendPort);
- receivePort.listen((dynamic message) {
- port.send(message);
- });
- }
- }
- void main() async {
- final ecg = FileRecorder();
- await ecg.start('hello.txt');
- ecg.record(List.generate(1000000, (i) => i));
- ecg.record(List.generate(1000000, (i) => i + 1000000));
- ecg.record(List.generate(1000000, (i) => i + 2000000));
- ecg.record(List.generate(1000000, (i) => i + 3000000));
- ecg.record(List.generate(1000000, (i) => i + 4000000));
- ecg.record(List.generate(1000000, (i) => i + 5000000));
- ecg.stop();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement