withStatsCacheLock<T> method

Future<T> withStatsCacheLock<T>(
  1. Future<T> fn()
)

Execute fn while holding the stats cache lock. Only one operation can hold the lock at a time.

Implementation

Future<T> withStatsCacheLock<T>(Future<T> Function() fn) async {
  // Wait for any existing lock to be released.
  while (_statsCacheLockFuture != null) {
    await _statsCacheLockFuture;
  }

  late void Function() releaseLock;
  _statsCacheLockFuture = Future<void>(() {
    // The completer is effectively resolved when releaseLock is called.
  });

  try {
    return await fn();
  } finally {
    _statsCacheLockFuture = null;
    // releaseLock is not needed in Dart's single-threaded model,
    // but we mirror the TS pattern for clarity.
  }
}