close method

Future<void> close()

Tear the session down: ask the worker to destroy the native session, quiesce, and close its callback (the worker owns the teardown ordering so commons never invokes a freed trampoline), then drop our port. When the worker is idle (the usual case — close runs after the final event) it processes this immediately and exits on its own.

Implementation

Future<void> close() async {
  if (_closed) return;
  _closed = true;
  final worker = _toWorker;
  if (worker != null) {
    worker.send('close');
  } else {
    // Worker not live yet — kill it once it spawns so it cannot leak.
    _isolate?.kill(priority: Isolate.immediate);
  }
  _toWorker = null;
  _fromWorker.close();
  await _events.close();
}