Skip to main content

Using distributed locks

This section provides information on how to acquire distributed locks in a command.

API reference:

Required scopes:

  • Data/Buildby.Taskurai/locks/create
  • Data/Buildby.Taskurai/locks/read
  • Data/Buildby.Taskurai/locks/delete

Prerequisites​

Acquiring a lock in a command​

In this example, a lock is acquired with id EuSalesLock for the owner SalesCollector.CollectEUSales with a lease time of 2 minutes, the call will wait 30 seconds to acquire a lock. If the call fails, an exception will be thrown.

[Command]
public async Task<double> CollectEUSales(TaskuraiTaskContext context, CancellationToken cancellationToken, string country)
{
await using (var distributedLock = await context.AcquireLockAsync(
lockId: "EuSalesLock",
owner: "SalesCollector.CollectEUSales",
ttl: TimeSpan.FromMinutes(2),
timeout: TimeSpan.FromSeconds(30)))
{
// Check if task may start after acquiring lock
context.CheckTaskExpired();

// Throw if lock is expired.
distributedLock.ThrowIfLockExpired();
}
}

Expiration status​

When using the notStartAfter setting in the task execution options in combination with distributed locks, it is recommended to check the expiration status using CheckTaskExpired after acquiring the lock.

// Check if task may start after acquiring lock
context.CheckTaskExpired();

Checking lock lease​

When running long operations is a lock, it is required to check if the lock lease is still active using the IsLocked(), IsLockedAsync() or ThrowIfLockExpired() methods on TaskuraiDistributedLock class.

// Throw if lock is expired.
distributedLock.ThrowIfLockExpired();