Skip to content

Search EricksonLopez.* Ecosystem

Type a library name, NuGet package ID, .NET type, or architectural concept to search across the portal.

Guides & Recipes — DistributedLock

Best-practice patterns for coordinating mutual exclusion safely under network partitions and lock-lease drops.

When using AcquireHandleAsync directly instead of ExecuteWithLockAsync, link handle.HandleLostToken with your request CancellationToken:

using System;
using System.Threading;
using System.Threading.Tasks;
using EricksonLopez.DistributedLock.Abstractions;
using EricksonLopez.Result;
namespace Example.DistributedLockRecipes;
public static class SafeHandleWorker
{
public static async Task<Result<bool>> ProcessWithHandleAsync(
IDistributedLockProvider provider,
string resourceId,
CancellationToken ct)
{
Result<IDistributedLockHandle> acquired = await provider.TryAcquireHandleAsync(
resourceId,
TimeSpan.FromSeconds(5),
ct);
if (acquired.IsFailure)
{
return Result<bool>.Failure(acquired.Error);
}
await using IDistributedLockHandle handle = acquired.Value;
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, handle.HandleLostToken);
linked.Token.ThrowIfCancellationRequested();
await Task.Delay(25, linked.Token);
return Result<bool>.Success(true);
}
}

DistributedLockExtensions.ExecuteWithLockAsync manages acquisition, HandleLostToken linking, and await using disposal automatically, returning Task<Result<T>> or Task<Result<bool>>.