الانتقال إلى المحتوى
.NETASP.NET Core· 8 دقائق للقراءة

Fire-and-Forget in a Request Handler: Why Work Gets Lost and What to Use Instead

A discarded Task.Run belongs to nobody: it borrows services from a finished request, its errors go unseen, and shutdown doesn't wait for it. Hand the work to a hosted service through a bounded queue.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

The checkout endpoint used to take two seconds because it sent the confirmation email before answering. A developer moves the email into _ = 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

The belief: calling 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.

It's easy to believe because most of it looks true. 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.

The flaw is ownership. A task belongs to nothing that knows when the request ends or when the app stops.

What actually happens

It borrows services from a request that's over

Scoped services, such as a 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

Nobody awaits the task, so nobody sees it fail. In the same test, the client got 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

When a deploy stops the app, the host signals its and waits for them to finish, up to a 30-second default timeout. Then the process exits. A task that isn't part of any hosted service just stops wherever it is. In a test, a three-second "send" started half a second before shutdown never completed and left no log line. The same work running in a hosted service kept the host alive until it finished.

Nothing limits how many run

Every request starts another task on the same pool that serves requests. A traffic spike becomes a spike of background work with nothing to slow it down, competing with the requests themselves.

The fix: queue the data, not the work

The request saves the order and hands off its id. Both versions use the same ShopDb, Order and IEmailSender:

C# Program.cs
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();

The worker reads ids from the channel and creates a fresh scope for each one, so every email gets its own ShopDb and IEmailSender:

C# ConfirmationWorker.cs
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);            }        }    }}

The bounded channel gives you : when 100 ids are waiting, WriteAsync waits for space instead of letting work pile up without limit.

_ = Task.Run(...)Channel + hosted serviceDurable queue
Scoped servicesBorrowed from a finished requestA new scope per itemA new scope per message
ErrorsLost silentlyLogged per itemLogged, and the message can be retried
Graceful shutdownNot waited forCurrent item finishes, up to the timeoutUnfinished messages stay in the queue
Crash or restartLostItems still in the channel are lostKept
Burst of requestsUnboundedWriters wait when fullAbsorbed by the queue

How to apply it in your project

  1. Find the unowned tasksSearch for _ = Task.Run, Task.Run( without an await, Task.Factory.StartNew and async void methods called from handlers. Each one is work nobody waits for.
  2. Hand off data, not servicesPass ids and plain values to the background side. Never capture HttpContext, a DbContext or any scoped service in a lambda that outlives the request.
  3. Add a bounded channel and a workerRegister a Channel.CreateBounded<T> as a singleton and a BackgroundService that creates a scope per item, logs failures and keeps going.
  4. Decide what a restart may loseIf 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.Run is 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 Channel plus a BackgroundService gives 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.

📚 المصادر

  1. Background tasks with hosted services in ASP.NET Core — Microsoft Learn
  2. ASP.NET Core Best Practices: Do not capture services on background threads — Microsoft Learn
  3. Create a queue service — .NET, Microsoft Learn
  4. .NET 6 breaking change: Exception handling in hosting — Microsoft Learn

التعليقات (0)