1Return the result from the handler
What the handler returns is stored with the job as its result.
public static class AddNumbersJob
{
[Job("add-numbers")]
public static AddNumbersResult Handle(AddNumbers input) => new(input.Left + input.Right);
}2Wait for the job and read its result
WaitAsync follows the job to its terminal state and carries the typed result.
var builder = Host.CreateApplicationBuilder(args);
builder.Services.UseActa(j =>
{
j.UseLocalDatabase(builder.Configuration);
j.Run<JobResultJobs>("job-result");
});
using var host = builder.Build();
await host.StartAsync();
var jobs = host.Services.GetRequiredService<IJobs>();
var handle = await jobs.EnqueueAsync(new AddNumbers(2, 3));
var result = (await handle.WaitAsync<AddNumbersResult>()).ValueOrThrow();
Console.WriteLine($"2 + 3 = {result.Sum}");
await host.StopAsync();3Run it and check the output
From a clone of the Acta repository, with the .NET 10 SDK:
dotnet run --project learn/000-fundamentals/003-job-result2 + 3 = 5Checked 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/003-job-result, 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.
job-result.cs47 lines
// How to return a result and wait for it
// What the handler returns is stored with the job as its result. `WaitAsync<T>` follows the job to its end and hands
// the result back, typed.
using Acta;
using Acta.Learn.JobResult;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
var builder = Host.CreateApplicationBuilder(args);
builder.Services.UseActa(j =>
{
j.UseLocalDatabase(builder.Configuration);
j.Run<JobResultJobs>("job-result");
});
using var host = builder.Build();
await host.StartAsync();
var jobs = host.Services.GetRequiredService<IJobs>();
var handle = await jobs.EnqueueAsync(new AddNumbers(2, 3));
// learn: 2. Wait for the job and read its result
// WaitAsync follows the job to its terminal state and carries the typed result.
var result = (await handle.WaitAsync<AddNumbersResult>()).ValueOrThrow();
Console.WriteLine($"2 + 3 = {result.Sum}");
// learn: end
await host.StopAsync();
namespace Acta.Learn.JobResult
{
public sealed record AddNumbers(int Left, int Right);
public sealed record AddNumbersResult(int Sum);
public static class AddNumbersJob
{
// learn: 1. Return the result from the handler
// What the handler returns is stored with the job as its result.
[Job("add-numbers")]
public static AddNumbersResult Handle(AddNumbers input) => new(input.Left + input.Right);
// learn: end
}
}