tryLock method
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 thelockwill 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;
}