How-to

Acquire a distributed lock

Applies to: .NET SDK Last updated: 2026-06-11

Goal

Ensure that only one swarm member at a time holds exclusive access to a shared resource (a task, a queue position, a counter).

Prerequisites

Swarm mode must be enabled (Enable swarm mode).

Code

await using var lockHandle = await client.SwarmLockManager!
    .TryAcquireLockAsync("task-batch-001");

if (lockHandle == null)
{
    // Another swarm member is holding this lock
    return;
}

// We have exclusive access
await DoWorkAsync();

// Lock auto-released when lockHandle is disposed

Refresh for long-running work

Locks automatically expire after 3 minutes if not refreshed, so a crashed holder doesn't block the swarm forever. For work that takes longer, call RefreshAsync periodically:

using var refreshTimer = new Timer(
    async _ => await lockHandle.RefreshAsync(),
    null,
    TimeSpan.FromMinutes(2),
    TimeSpan.FromMinutes(2));

await DoLongRunningWorkAsync();

See also