ASP.NET Core

Task.Run Does Not Make ASP.NET Core Work Durable

ASI Backbone Learning Christopher D. Cavell
ASP.NET Core

Returning 202 Accepted and starting the work with `Task.Run` makes an endpoint fast, but the work lives only in that process: nothing coordinates it with shutdown, it may touch a disposed request-scoped service, and its failures go unrecorded. The article separates the three guarantees an endpoint can choose from and what each one actually promises.

Key points

  • Detached work, host-managed execution and durable acceptance are three distinct guarantee levels; `Task.Run` only schedules on the thread pool.
  • A `BackgroundService` owns the work, but graceful shutdown is bounded by `HostOptions.ShutdownTimeout` (30 seconds by default) and adds no durability.
  • Using a scoped service such as `DbContext` in detached work after the request scope is disposed throws `ObjectDisposedException`; each work item needs its own scope.
  • An unobserved task keeps its exception on the task; `TaskScheduler.UnobservedTaskException` fires at nondeterministic times and is no substitute for logging it.
  • A bounded in-memory queue brings backpressure, failure recording and a shutdown path that reports what it abandons.
  • The durable option records the job before answering, so a status resource with a stable identifier can be queried later.

Real-world use

  • A report endpoint that reads thousands of ledger lines, renders a PDF and emails it at month-end close
  • Background work that calls a scoped service depending on the EF Core `DbContext` to reuse an existing query
  • A multi-instance API where accepted work must not vanish during a rolling deployment
  • A capacity-limited worker that must reject or slow down new work when its queue is full

This summary was generated by the agent from the original post on ASI Backbone Learning. The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message