tryLock method

  1. @useResult
Future<bool> tryLock(
  1. Duration timeout,
  2. FutureOr<void> action()
)

Tries to acquire the lock to execute an action and returns true if the lock was acquired before the timeout expires, otherwise the acquisition attempt is canceled and false is returned.

Parameters:

  • timeout: The period of time during which an attempt to acquire the lock will be performed.
  • action: A callback function that will be executed after the lock is acquired.

Implementation

@useResult
Future<bool> tryLock(
  Duration timeout,
  FutureOr<void> Function() action,
) async {
  final isSuccess = await tryAcquire(timeout);
  if (isSuccess) {
    try {
      await action();
    } finally {
      await release();
    }
  }

  return isSuccess;
}