jpnurmi / libserialport.dart

Serial Port for Dart
https://pub.dev/packages/libserialport
GNU Lesser General Public License v3.0
86 stars 34 forks source link

Fix: Isolate can't be killed on "onPause", and increases infinitely. #82

Open harajune opened 9 months ago

harajune commented 9 months ago

As stated in #46, SerialPortReader fails to kill Isolate on the "onPause"` event and creates a new one on the "onResume" event. So, Isolates increase infinitely.

Below is the example code to reproduce the problem. You'll see the increased Isolates in the call stack pane, as in the picture.

I'm not sure, but the onPause and onResume events are unnecessary, because the serial port can buffer input data.

Or, if SerialPortReader needs to handle resume/pause events, _isolate?.kill(priority: Isolate.immediate); also works well.

import 'dart:typed_data';

import 'package:libserialport/libserialport.dart';

// ignore_for_file: avoid_print

void main() async {
  print('Available ports:');
  var i = 0;
  for (final name in SerialPort.availablePorts) {
    final sp = SerialPort(name);
    print('${++i}) $name');
    print('\tDescription: ${sp.description}');
    print('\tManufacturer: ${sp.manufacturer}');
    print('\tSerial Number: ${sp.serialNumber}');
    print('\tProduct ID: 0x${sp.productId!.toRadixString(16)}');
    print('\tVendor ID: 0x${sp.vendorId!.toRadixString(16)}');
    sp.dispose();
  }

  final _port = SerialPort("COM3");

  final config = SerialPortConfig();
  config.baudRate = 9600;
  config.bits = 8;
  config.parity = 0;
  _port.config = config;
  _port.openRead();

  final _reader = SerialPortReader(_port);

  final stream = _reader.stream;

  await for (var data in testFunc(stream)) {
    print(data);
  }
}

Stream<String> testFunc(Stream<Uint8List> stream) async* {
  await for (var data in stream) {
    final s = String.fromCharCodes(data);
    yield s; // this emits the onPause event but SerialPortReader can't kill Isolate properly
  }
}

screenshot