Acta. Durable execution for .NET

learn actadecide what happens when work fails

How to stop cleanly when a job is cancelled

A handler takes a CancellationToken and passes it to everything it awaits, so a cancel, a timeout, or a shutdown that outlasts the host's grace period ends it promptly.

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

Checked every release learn/000-fundamentals/008-cancellation-token
Read as

1Check the token between pieces of work, and pass it to what you await

The token trips on an operator's cancel, at the ExecutionTimeout, on a lost lease, and on a shutdown once the host's ShutdownTimeout has passed. A handler that ignores it keeps running after the worker has been told to stop.

cancellation-token.csexcerpt
public static class ImportJob
{
    // Acta trips the CancellationToken on shutdown or lease loss; the handler must observe it.
    [Job("slow-import")]
    public static async Task Handle(SlowImport input, CancellationToken ct)
    {
        for (var batch = 1; batch <= input.Batches; batch++)
        {
            ct.ThrowIfCancellationRequested();
            await Task.Delay(100, ct);
            Console.WriteLine($"Imported batch {batch}/{input.Batches}");
        }
    }
}

2Run it and check the output

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

Terminal
dotnet run --project learn/000-fundamentals/008-cancellation-token
Its output must contain
Imported batch 3/3

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

This page shows the code. The rules it relies on, starting with the handler running again from its first line, are in the handler contract.

The whole program

Every file of learn/000-fundamentals/008-cancellation-token, 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.

cancellation-token.cs51 lines
cancellation-token.cs
// How to stop cleanly when a job is cancelled
// A handler takes a `CancellationToken` and passes it to everything it awaits, so a cancel, a timeout, or a shutdown
// that outlasts the host's grace period ends it promptly.
using Acta;
using Acta.Learn.Cancellation;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = Host.CreateApplicationBuilder(args);

builder.Services.UseActa(j =>
{
    j.UseLocalDatabase(builder.Configuration);
    j.Run<CancellationJobs>("cancellation-token");
});

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

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

await jobs.EnqueueAsync(new SlowImport(3));
Console.WriteLine("Enqueued. Worker is running - press Ctrl+C to stop.");

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

namespace Acta.Learn.Cancellation
{
    public sealed record SlowImport(int Batches);

    public static class ImportJob
    {
        // Acta trips the CancellationToken on shutdown or lease loss; the handler must observe it.
        [Job("slow-import")]
        public static async Task Handle(SlowImport input, CancellationToken ct)
        {
            for (var batch = 1; batch <= input.Batches; batch++)
            {
                // learn: Check the token between pieces of work, and pass it to what you await
                // The token trips on an operator's cancel, at the `ExecutionTimeout`, on a lost lease, and on a shutdown
                // once the host's `ShutdownTimeout` has passed. A handler that ignores it keeps running after the
                // worker has been told to stop.
                ct.ThrowIfCancellationRequested();
                await Task.Delay(100, ct);
                // learn: end
                Console.WriteLine($"Imported batch {batch}/{input.Batches}");
            }
        }
    }
}

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.