Acta. Durable execution for .NET

learn actacontrol order and load

How to let one job at a time touch a resource

RunWithLockAsync holds a named lock around a piece of work, so jobs that name the same lock take turns.

A how-to for Acta, durable execution for .NET. New to Acta? Run your first durable job in five minutes.

Checked every release learn/200-durable-execution/207-run-with-lock
Read as

1Run the work under a named lock

Named lock held for the action; same key serializes both concurrently-running jobs. To exclude the whole job instead, set ConcurrencyKey on enqueue (see 209-concurrency-key).

run-with-lock.csexcerpt
public sealed class UpdateInventoryJob
{
    [Job("update-inventory")]
    public async Task Handle(UpdateInventory input, JobContext context, CancellationToken ct)
    {
        await context.RunWithLockAsync(
            "inventory",
            async token =>
            {
                Console.WriteLine($"[{input.Sku}] acquired lock, updating inventory...");
                await Task.Delay(1000, token);
                Console.WriteLine($"[{input.Sku}] done, releasing lock");
            },
            ct: ct
        );
    }
}

2Run it and check the output

From a clone of the Acta repository, with the .NET 10 SDK:

Terminal
dotnet run --project learn/200-durable-execution/207-run-with-lock
Its output must contain
[sku-A] done, releasing lock
[sku-B] done, releasing lock

Checked every release. Before each release, Acta Verify runs this program and checks that its output contains these lines.

Remember

  • Acquiring the lock waits about 30 seconds, the timeout: argument, before it throws LockAcquisitionTimeoutException.
  • The hold renews with the holder's heartbeat, so a dead holder keeps the lock for up to one lease.

The whole program

Every file of learn/200-durable-execution/207-run-with-lock, as it is compiled.

UseLocalDatabase is a helper of the Acta repository, not of the packages. In your own app, register the database with UseSqlite, UsePostgres or UseSqlServer, as in how to run your first job.

run-with-lock.cs53 lines
run-with-lock.cs
// How to let one job at a time touch a resource
// `RunWithLockAsync` holds a named lock around a piece of work, so jobs that name the same lock take turns.
using Acta;
using Acta.Learn.RunWithLock;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = Host.CreateApplicationBuilder(args);

builder.Services.UseActa(j =>
{
    j.UseLocalDatabase(builder.Configuration);
    j.Run<RunWithLockJobs>("run-with-lock");
});

using var host = builder.Build();
await host.StartAsync();

var jobs = host.Services.GetRequiredService<IJobs>();

// Both jobs share a lock key, so they take turns.
await jobs.EnqueueAsync(new UpdateInventory("sku-A"));
await jobs.EnqueueAsync(new UpdateInventory("sku-B"));
Console.WriteLine("Enqueued 2 jobs. Worker is running - press Ctrl+C to stop.");

await host.WaitForShutdownAsync();
await host.StopAsync();

namespace Acta.Learn.RunWithLock
{
    public sealed record UpdateInventory(string Sku);

    public sealed class UpdateInventoryJob
    {
        [Job("update-inventory")]
        public async Task Handle(UpdateInventory input, JobContext context, CancellationToken ct)
        {
            // learn: Run the work under a named lock
            // Named lock held for the action; same key serializes both concurrently-running jobs. To exclude the whole job instead, set ConcurrencyKey on enqueue (see 209-concurrency-key).
            await context.RunWithLockAsync(
                "inventory",
                async token =>
                {
                    Console.WriteLine($"[{input.Sku}] acquired lock, updating inventory...");
                    await Task.Delay(1000, token);
                    Console.WriteLine($"[{input.Sku}] done, releasing lock");
                },
                ct: ct
            );
            // learn: end
        }
    }
}

Where to go next

New to Acta?

Acta is durable execution for .NET: workflows and jobs that survive restarts, as a library inside your application with its durable state in your SQL database.