In an ASP.NET Core endpoint, why is `_ = Task.Run(...)` after a photo upload a poor way to render thumbnails, and what replaces it?
answer
- the request scope ends first
- ObjectDisposedException from the DbContext
- TaskScheduler.UnobservedTaskException, nobody logs
- host shutdown ignores the task
- no limit under a burst
basics
~20 sThe task outlives the request: scoped services it captured are disposed, its exceptions go unobserved, the host neither tracks nor waits for it at shutdown, and a burst starts unlimited renders. A Channel drained by a BackgroundService replaces it.
solid answer
~50 s`_ = Task.Run(() => renderer.RenderAsync(db, id))` returns at once and the response goes out, but the work is now an orphan. It captured the request's scoped `DbContext`, which ASP.NET Core disposes when the request scope ends, so the render often fails with `ObjectDisposedException` ("Cannot access a disposed context instance"). Its exceptions land on a task nobody awaits: no log line, at most `TaskScheduler.UnobservedTaskException` when the task is collected. At shutdown the host waits only for hosted services, so a render in progress is cut off and the job is gone. Under a burst, every upload starts another CPU-heavy render at once, with no queue and no limit. The replacement is a bounded `Channel<T>` written by the endpoint and drained by a `BackgroundService` that creates a scope per job: the work has a lifetime, a limit, logging and a shutdown hook.
code
csharp · 22 linespublic sealed class ThumbnailWorker(
ChannelReader<ThumbnailJob> jobs,
IServiceScopeFactory scopeFactory,
ILogger<ThumbnailWorker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await foreach (var job in jobs.ReadAllAsync(stoppingToken))
{
try
{
await using var scope = scopeFactory.CreateAsyncScope();
var renderer = scope.ServiceProvider.GetRequiredService<ThumbnailRenderer>();
await renderer.RenderAsync(job.PhotoId, stoppingToken);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogError(ex, "Thumbnail rendering failed for {PhotoId}", job.PhotoId);
}
}
}
}go deeper
Recall that work started with Task.Run in a handler outlives the request, so scoped services like the DbContext may already be disposed.
Explain the four failure modes, disposed scope, unobserved exceptions, no shutdown wait and no limit, and how a channel plus hosted consumer addresses each.
Spot fire-and-forget in code review, trace a production ObjectDisposedException or missing thumbnail back to it, and replace it with an owned, bounded consumer.
Set a team rule for post-response work: an owner with a lifetime and a limit, and a durable mechanism whenever losing the work is not acceptable.
## What the code looks like A common first attempt at "do it in the background": ```csharp app.MapPost("/photos/{id:guid}/publish", async (Guid id, PhotoDbContext db, ThumbnailRenderer renderer) => { var photo = await db.Photos.FindAsync(id); photo!.Published = true; await db.SaveChangesAsync(); _ = Task.Run(() => renderer.RenderAsync(db, id)); // fire and forget return TypedResults.Accepted($"/photos/{id}"); }); ``` It works in a demo. In production it fails in several ASP.NET Core-specific ways. ## 1. The request scope is disposed underneath it Every request gets a DI scope, and services registered as scoped, such as the `DbContext` from `AddDbContext`, live in it. When the response completes, ASP.NET Core disposes that scope and every scoped service in it. The background task still holds a reference to `db`, so whether the render succeeds depends on a race: if it reaches the database after disposal, EF Core throws `ObjectDisposedException` with "Cannot access a disposed context instance". The request's `HttpContext` is just as unsafe to touch once the response is done. ## 2. Exceptions disappear The discarded `Task` is never awaited, so its exception is never observed: - no exception handler middleware sees it, because the response has already been sent; - nothing logs it unless the lambda has its own `try`/`catch`; - the runtime raises `TaskScheduler.UnobservedTaskException` only if and when the faulted task is garbage-collected, and by default it does not crash the process. A hosted service's failure, by contrast, is logged by the host and handled by `BackgroundServiceExceptionBehavior`. ## 3. Shutdown does not know it exists On a graceful shutdown the host calls `StopAsync` on each registered `IHostedService` and waits up to the shutdown timeout. A task started with `Task.Run` is invisible to that sequence. When the process exits, a half-finished render is abandoned and nothing records that the photo still needs thumbnails. Deployments trigger exactly this several times a day. ## 4. No limit and no back-pressure Each upload starts its own render on the thread pool. A burst of 200 uploads means 200 concurrent CPU-heavy renders competing with request processing, inflating latency for every endpoint. There is nowhere to say "at most four at a time" or "refuse new work when 500 are pending". ## Spotting it in code review - A discard `_ = Task.Run(...)` or an un-awaited call to an `async` method inside a handler, controller action or Razor Page handler. - A lambda that captures injected request services (`db`, a repository, `HttpContext`, `IHttpContextAccessor`). - `async void` methods used to start background work, which crash the process on an exception instead of going unobserved. - A comment like "don't await, it's slow". ## The replacement | Concern | `Task.Run` fire-and-forget | Channel + `BackgroundService` | |---|---|---| | Lifetime of services | captures the request's scoped objects | consumer creates a scope per job | | Errors | unobserved | caught and logged in the consumer loop | | Shutdown | cut off silently | consumer's `StopAsync` can drain within the timeout | | Concurrency | one task per request | fixed number of readers | | Overload | unlimited growth | bounded capacity, `503` when full | The endpoint writes a small job (the photo id) to a singleton bounded `Channel<ThumbnailJob>` and returns. A `BackgroundService` reads with `ReadAllAsync`, opens `IServiceScopeFactory.CreateAsyncScope()` per job, resolves a fresh `DbContext` from that scope, and logs failures. The work is still in memory and still lost if the process crashes, but it is now owned, limited and visible; durability is the next step when the work must survive restarts.
- Is copying the needed values into locals before Task.Run enough to make fire-and-forget safe?It removes the disposed-scope failure, but not the rest. Exceptions are still unobserved, the host still does not wait for the task at shutdown, and a burst still starts unlimited concurrent work. Those three problems need an owner with a lifetime, which in ASP.NET Core is a hosted service.
- Why does a fire-and-forget failure not crash the process, while a BackgroundService failure can stop the app?A faulted task that nobody awaits is only reported through `TaskScheduler.UnobservedTaskException` when it is collected, which does not terminate the process by default. A `BackgroundService`'s task is awaited by the host, which logs the fault and, under the default `BackgroundServiceExceptionBehavior.StopHost`, stops the application.
- Task.Run copies the injected DbContext, so using it later is safe
- IExceptionHandler will log failures from the fire-and-forget task
- The host waits for every Task.Run task before shutting down
- Fire-and-forget limits itself because the thread pool queues the work
- An unobserved task exception crashes the ASP.NET Core process by default