
Fire-and-Forget in a Request Handler: Why Work Gets Lost and What to Use Instead
- كاتب موثّق
- .NET 10
محتويات المقال
_ = Task.Run(...), and the endpoint now returns 202 Accepted in a few milliseconds. Weeks later, support forwards a pattern: some customers never get their confirmation, and the missing ones cluster around deploy times and busy hours. The logs show successful POST /orders requests and nothing else. No exception, no warning, no trace of the email at all.
The common misconception
Task.Run without awaiting it is how you do background work in ASP.NET Core. The response goes out right away, the work continues on another thread, and the runtime makes sure it finishes.
Task.Run does queue the work to the , and it does keep running after the response is sent. On a developer machine it usually finishes, since nothing restarts the process mid-send. And classic ASP.NET had HostingEnvironment.QueueBackgroundWorkItem, which tracked work like this for you. That API was deliberately not ported to .NET, but the habit it created survived.
What actually happens
It borrows services from a request that's over
DbContext, belong to the request's scope, and that scope is disposed when the request completes. The lambda still holds references to them. In a test with EF Core's in-memory provider, a background read through the request's context threw ObjectDisposedException for 200 requests out of 200, even with no delay before the read: the response finished first every time. The best practices page warns about exactly this, and about capturing HttpContext, which is recycled after the request.
Its exceptions disappear
202 and ASP.NET Core logged nothing at all. The exception only surfaced through TaskScheduler.UnobservedTaskException after a forced garbage collection, an event almost no app handles.
Shutdown doesn't wait for it
Nothing limits how many run
The fix: queue the data, not the work
ShopDb, Order and IEmailSender:
using Microsoft.EntityFrameworkCore;var builder = WebApplication.CreateBuilder(args);builder.Services.AddDbContext<ShopDb>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Shop")));builder.Services.AddScoped<IEmailSender, SmtpEmailSender>();var app = builder.Build();app.MapPost("/orders", async (Order order, ShopDb db, IEmailSender email) =>{ db.Orders.Add(order); await db.SaveChangesAsync(); _ = Task.Run(async () => // owned by nobody once the response is sent { var customer = await db.Customers.FindAsync(order.CustomerId); await email.SendConfirmationAsync(customer!.Email, order.Id); }); return Results.Accepted();});app.Run();using System.Threading.Channels;using Microsoft.EntityFrameworkCore;using Shop.Orders;var builder = WebApplication.CreateBuilder(args);builder.Services.AddDbContext<ShopDb>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Shop")));builder.Services.AddScoped<IEmailSender, SmtpEmailSender>();builder.Services.AddSingleton(Channel.CreateBounded<int>(100)); // full: writers waitbuilder.Services.AddHostedService<ConfirmationWorker>();var app = builder.Build();app.MapPost("/orders", async (Order order, ShopDb db, Channel<int> queue) =>{ db.Orders.Add(order); await db.SaveChangesAsync(); await queue.Writer.WriteAsync(order.Id); // hand off data, never services return Results.Accepted();});app.Run();ShopDb and IEmailSender:
using System.Threading.Channels;namespace Shop.Orders;public sealed class ConfirmationWorker(Channel<int> queue, IServiceScopeFactory scopes, ILogger<ConfirmationWorker> logger) : BackgroundService{ protected override async Task ExecuteAsync(CancellationToken stoppingToken) { await foreach (var orderId in queue.Reader.ReadAllAsync(stoppingToken)) { try { await using var scope = scopes.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService<ShopDb>(); var email = scope.ServiceProvider.GetRequiredService<IEmailSender>(); var order = await db.Orders.FindAsync(orderId); var customer = await db.Customers.FindAsync(order!.CustomerId); await email.SendConfirmationAsync(customer!.Email, orderId); } catch (Exception ex) // logged per item; the worker keeps going { logger.LogError(ex, "Confirmation for order {OrderId} failed", orderId); } } }}WriteAsync waits for space instead of letting work pile up without limit.
_ = Task.Run(...) | |||
|---|---|---|---|
How to apply it in your project
Find the unowned tasks Search for _ = Task.Run,Task.Run(without anawait,Task.Factory.StartNewandasync voidmethods called from handlers. Each one is work nobody waits for.Hand off data, not services Pass ids and plain values to the background side. Never capture HttpContext, aDbContextor any scoped service in a lambda that outlives the request.Add a bounded channel and a worker Register a Channel.CreateBounded<T>as a singleton and aBackgroundServicethat creates a scope per item, logs failures and keeps going.Decide what a restart may lose If losing queued items on a deploy is acceptable, the channel is enough. If not, persist the job with the data it belongs to and process it from there.
Key takeaways
A discarded Task.Runis owned by nothing: not the request, not the host.Scoped services captured from the request are disposed when it ends, so the background work fails, often every time. Its exceptions are never observed and never logged, and shutdown doesn't wait for it. A bounded Channelplus aBackgroundServicegives each item its own scope, logging, backpressure and a graceful stop.An in-memory queue still loses waiting items on a restart; store work that must not be lost.
التعليقات (0)