Skip to content

LockAsync

Asynchronously attempts to acquire a lock without blocking the script execution thread while waiting.

1
$Cache.LockAsync(key: string, blockingTimeout?: string, duration?: string, tryLockInterval?: string):Promise<( string | `"null"` )>

Parameters

string key
    The lock key, which is a unique identifier for shared access.

string blockingTimeout optional
    The maximum duration to wait in "hh:mm:ss" format. The default is 60 seconds.

string duration optional
    The lock lifetime in "hh:mm:ss" format.

string tryLockInterval optional
    The interval between acquisition attempts in "hh:mm:ss" format.

Returns

A promise containing the acquired token, or null when the timeout expires.

Remarks

Prefer this method over $Cache.Lock in asynchronous scripts.

Waiting asynchronously for up to 30 seconds and always releasing the acquired lock

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var tokenValue = await $Cache.LockAsync('mylock', '00:00:30');
if (tokenValue == null) {
  // The lock was not available before the timeout expired
} else {
  try {
    // Locked code block
  }
  finally {
    await $Cache.ReleaseLockAsync('mylock', tokenValue);
  }
}

Configuring the wait time, lock lifetime, and interval between acquisition attempts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
var tokenValue = await $Cache.LockAsync(
  'report-generation',
  '00:00:10', // Wait for up to 10 seconds
  '00:02:00', // Keep the lock for up to 2 minutes
  '00:00:01'  // Retry every second
);

if (tokenValue != null) {
  try {
    // Generate the shared report
  }
  finally {
    await $Cache.ReleaseLockAsync('report-generation', tokenValue);
  }
}

See Also