dispose method

Future<void> dispose()

Kills the worker isolate and closes results. Idempotent.

Implementation

Future<void> dispose() async {
  if (_disposed) return;
  _disposed = true;
  if (_direct) {
    // Cancel the worker's native subscription before the kill, so the native
    // side releases the port instead of posting to a dead one.
    final done = ReceivePort();
    _toWorker?.send(_Detach(done.sendPort));
    await done.first.timeout(const Duration(milliseconds: 500), onTimeout: () => null);
    done.close();
  }
  _isolate?.kill(priority: Isolate.immediate);
  _isolate = null;
  _releaseBuffer(_pending?.nativeBuffer ?? 0);
  _releaseBuffer(_inFlightBuffer);
  _inFlightBuffer = 0;
  _pending = null;
  if (!_out.isClosed) await _out.close();
  if (!_stats.isClosed) await _stats.close();
}