Skip to content

Lock

Attempts to acquire a lock for the specified key, blocking until the lock is acquired.

1
$Cache.Lock(key: string):( string | null )

Attempts to acquire a lock for the specified key, blocking for a specified duration until the lock is acquired or the timeout expires.

1
$Cache.Lock(key: string, blockingTimeout: string, duration?: string, tryLockInterval?: string):( string | null )

Parameters

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

string blockingTimeout
    The duration to wait for the lock in "hh:mm:ss" format. The default value is 60 seconds.

string duration optional
    How long the lock is held before it expires automatically, in "hh:mm:ss" format. The default value is 5 minutes.

string tryLockInterval optional
    How often the lock is tried again while waiting, in "hh:mm:ss" format. The default value is 500 milliseconds.

Returns

The acquired lock token if successful; otherwise, null.

Remarks

This method automatically enters a wait state until the shared key is free or the timeout is reached. If you do not want to wait, use the $Cache.TryLock method instead.

Acquired locks must always be released using the $Cache.ReleaseLock method with the generated token value. The token proves ownership; a different token cannot release the lock. Otherwise, the lock remains held until its configured or provider default duration expires.

Examples

Generate a unique sequence number

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
var token = $Cache.Lock('InvoiceNumber');

try {
    var result = $Database.Get({
        TargetSchema : 'Sales',
        TargetTable : 'Invoices',
        Columns : [{ Name : 'Number', Expression : 'Max(Number)' }]
    });

    var last = result.Length > 0 ? (result[0]['Number'] || 0) : 0;
    $Xml.SetValue('InvoiceNumber', last + 1);
}
finally {
    $Cache.ReleaseLock('InvoiceNumber', token);
}

Wait up to 30 seconds for a lock

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
var key = 'Stock:' + $Xml.Evaluate('ProductId');
var token = $Cache.Lock(key, '00:00:30');

if (token == null) {
    throw new Error('The stock record is busy. Please try again.');
}

try {
    // update the stock record
}
finally {
    $Cache.ReleaseLock(key, token);
}

See Also