withLock method

FutureOr<void> withLock(
  1. FutureOr<void> action(), {
  2. String? waiting,
})

creates a lock file and then calls action once action 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

FutureOr<void> withLock(
  FutureOr<void> Function() action, {
  String? waiting,
}) async {
  final callingStackTrace = Trace.current();

  final execution = runtime.ExecutionCall<FutureOr<void>, DCliException>(
    callable: () => action(),
    safe: true,
  );

  try {
    verbose(() => 'withLock called for $_nameWithSuffix');

    // Note that guarded here is the same insance as execution above
    final _execution = runtime.NamedLock.guard<FutureOr<void>, DCliException>(
      name: _nameWithSuffix,
      execution: execution,
      waiting: waiting,
      timeout: _timeout,
    );

    if (_execution.successful.isSet && _execution.successful.get!) {
      await _execution.completer.future;
      await _execution.returned;
    } else if (_execution.error.isSet) {
      await _execution.error.get?.rethrow_();
    }
  } on DCliException catch (e) {
    verbose(() => 'Exception caught for $_nameWithSuffix...  $e : $e');
    throw e..stackTrace = callingStackTrace;
  } on Exception catch (e) {
    verbose(() => 'Exception caught for $_nameWithSuffix... $e : $e');
    throw DCliException.from(e, callingStackTrace);
  } finally {
    verbose(() => 'withLock completed for $_nameWithSuffix');
  }
}