A task is a long-running request the client polls by ID. EfTaskStore saves its status and result in SQLite, not the running work.
dotnet add package RecursiveAI.OneModelContext.EntityFrameworkCore dotnet add package Microsoft.EntityFrameworkCore.Sqlite
Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.
#pragma warning disable OMCX0001 using Microsoft.EntityFrameworkCore; using RecursiveAI.OneModelContext; using RecursiveAI.OneModelContext .EntityFrameworkCore; using RecursiveAI.OneModelContext .Extensions.Tasks; var db = new JobDatabase(); using var context = db.CreateDbContext(); context.Database.EnsureCreated(); var server = new ContextServer( "Jobs", "1.0"); server.UseTasks(new TaskServerOptions { Store = new EfTaskStore<JobDatabase>(db) }); Console.WriteLine("Task store configured."); sealed class JobDatabase : DbContext, IDbContextFactory<JobDatabase> { public JobDatabase CreateDbContext() => new(); protected override void OnConfiguring( DbContextOptionsBuilder options) => options.UseSqlite( "Data Source=jobs.db"); protected override void OnModelCreating( ModelBuilder model) => model.ApplyTaskStore(); }
Creates jobs.db, configures the server, and prints Task store configured. Use a fresh database file: EnsureCreated() won’t add the task table to a database that already has tables. The Tasks extension is experimental; OMCX0001 is its opt-in.
The full program shows the saved status surviving a process restart: Saved: completed, then Reopened: completed.
Unzip the example, then dotnet run.
The full program
To show persistence without a network or client, the example calls the task store directly. A child process adds 3 and 7 and saves a completed sum-demo record in a new SQLite file. After the child exits, the parent opens that same file, reads the status and result, and deletes the file. No input files are needed.
#pragma warning disable OMCX0001 using System.Diagnostics; using Microsoft.EntityFrameworkCore; using RecursiveAI.OneModelContext.EntityFrameworkCore; using RecursiveAI.OneModelContext.Extensions.Tasks; if (args is ["write", var file]) { var db = new JobDatabase(file); await using var context = db.CreateDbContext(); await context.Database.EnsureCreatedAsync(); var store = new EfTaskStore<JobDatabase>(db); var now = DateTimeOffset.UtcNow; var total = new[] { 3, 7 }.Sum(); await store.CreateAsync(new TaskRecord { TaskId = "sum-demo", Owner = "", ToolName = "sum", Status = TaskStates.Completed, CreatedAt = now, LastUpdatedAt = now, ResultJson = $$"""{"content":[{"type":"text","text":"{{total}}"}]}""" }); Console.WriteLine("Saved: completed"); return; } var path = Path.GetFullPath($"tasks-{Guid.NewGuid():N}.db"); try { var start = new ProcessStartInfo(Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet") { ArgumentList = { typeof(Program).Assembly.Location, "write", path } }; using var writer = Process.Start(start) ?? throw new InvalidOperationException("Could not start writer."); await writer.WaitForExitAsync(); if (writer.ExitCode != 0) throw new InvalidOperationException("The writer failed."); var store = new EfTaskStore<JobDatabase>(new JobDatabase(path)); var task = await store.GetAsync("sum-demo") ?? throw new InvalidOperationException("Task not found."); Console.WriteLine($"Reopened: {task.Status}"); Console.WriteLine(task.ResultJson); } finally { File.Delete(path); } sealed class JobDatabase(string path) : DbContext, IDbContextFactory<JobDatabase> { public JobDatabase CreateDbContext() => new(path); protected override void OnConfiguring(DbContextOptionsBuilder options) => options.UseSqlite(new Microsoft.Data.Sqlite.SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString()); protected override void OnModelCreating(ModelBuilder model) => model.ApplyTaskStore(); }
Saved: completed Reopened: completed {"content":[{"type":"text","text":"10"}]}
At the default capacity of 10,000 records, a new insert can throw InvalidOperationException; the count is checked before insertion, so simultaneous writers can overshoot it.
Variations
For a small standalone database, pass the capacity to the store constructor. The example’s single record still fits:
var store = new EfTaskStore<JobDatabase>( db, capacity: 100);
Related recipes
The short answer
Apply ApplyTaskStore() in your EF Core model, and put an EfTaskStore<TContext> in TaskServerOptions.Store. Use a relational provider and keep the same database when the server restarts. The database keeps task IDs, status, and any saved results or errors; it does not restart interrupted work.
What happens to a long-running job when the server restarts?
A completed job’s saved status and result remain in the database until the record is removed. A client can poll for the same task ID after reconnecting, provided it uses the same principal and the record still exists. This example starts with a completed task so you can see the difference between reading saved results and running a job again.
If a worker process dies midway through a task, the store has no worker heartbeat or way to resume that computation. The extension docs say, “A task whose worker is gone stays working until its TTL.” The server’s default task time to live is one hour. Put a timeout on the client’s polling rather than treating working as proof that a worker is still alive.
Where should I store task state when multiple server instances can read it?
Point the instances at the same relational database. One instance can poll a task created by another. To avoid losing updates, the store only writes a change if the record still has the version that the caller read. The instance doing the work picks up answers and cancellation requests when it next reads the row. See Tasks across instances.
Use EnsureCreated() only for a database dedicated to this model, as in the sample. For a database you already manage with EF Core migrations, generate a migration instead. EF Core’s in-memory provider doesn’t support the relational update and delete operations this store needs. The EF Core adapter builds its model by reflection, so don’t use it for a NativeAOT build. The OneModelContext SDK has no native dependencies, but the SQLite provider used in this recipe includes native SQLite binaries. See the store setup and provider requirements.