withLock method

void withLock(
  1. void fn(), {
  2. String? waiting,
})

creates a lock file and then calls fn once fn returns the lock is released. If waiting is passed it will be used to write a log message to the console.

Throws a DCliException if the NamedLock times out.

Implementation

void withLock(
  void Function() fn, {
  String? waiting,
}) {
  final callingStackTrace = StackTraceImpl();
  var lockHeld = false;
  runZonedGuarded(() {
    try {
      verbose(() => 'lockcount = $_lockCountForName');

      _createLockPath();

      if (_lockCountForName > 0 || _takeLock(waiting)) {
        lockHeld = true;
        incLockCount;

        fn();
      }
    } finally {
      if (lockHeld) {
        _releaseLock();
      }
      // just in case an async exception can be thrown
      // I'm uncertain if this is a reality.
      lockHeld = false;
    }
  }, (e, st) {
    if (lockHeld) {
      _releaseLock();
    }
    // final stackTrace = StackTraceImpl.fromStackTrace(st);
    verbose(() => 'Exception throw $e : $e');
    if (e is DCliException) {
      throw e..stackTrace = callingStackTrace;
    } else {
      throw DCliException.from(e, callingStackTrace);
    }
  });
}