Implementing Background Work in ASP.NET Core
π‘ Concept Name
IHostedService / BackgroundService Pattern
π Quick Intro
ASP.NET Core supports background tasks using the `IHostedService` or `BackgroundService` interfaces. These services are started when the application launches and run in the background, independent of HTTP requests.
π§ Analogy / Short Story
Imagine a web app as a coffee shop. The HTTP requests are customer orders. But behind the scenes, you have a dishwasher that runs continuouslyβquietly cleaning up, independent of customer interactions. Thatβs your `BackgroundService`βdoing essential work behind the curtain.
π§ Technical Explanation
- π IHostedService: Interface to manage background task lifecycle (start/stop).
- π¦ BackgroundService: Abstract base class implementing IHostedService with a `ExecuteAsync()` method.
- β²οΈ Runs independently of HTTP pipeline, useful for polling, message queues, or scheduled work.
- π§΅ Tasks run on background threads with graceful shutdown support via `CancellationToken`.
- π‘οΈ Automatically managed by ASP.NET Core's built-in DI system.
π― Purpose & Use Case
- β Queue processing (e.g., RabbitMQ, Azure Service Bus).
- β Background file cleanup or report generation.
- β Scheduled tasks using timers or CRON-like logic.
- β Heartbeat monitoring or health checks.
π» Real Code Example
Hereβs a simple implementation using BackgroundService
:
public class WorkerService : BackgroundService
{
private readonly ILogger<WorkerService> _logger;
public WorkerService(ILogger<WorkerService> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Background task running at: {time}", DateTimeOffset.Now);
await Task.Delay(5000, stoppingToken);
}
}
}
// In Program.cs or Startup.cs
builder.Services.AddHostedService<WorkerService>();

β Interview Q&A
Q1: How do you implement a background task in ASP.NET Core?
A: Use IHostedService
or BackgroundService
.
Q2: Whatβs the difference between IHostedService and BackgroundService?
A: BackgroundService is an abstract class simplifying IHostedService with an ExecuteAsync
method.
Q3: Are background services tied to HTTP requests?
A: No, they run independently of HTTP pipelines.
Q4: How do you stop a background task gracefully?
A: Use the CancellationToken
passed to ExecuteAsync
.
Q5: Where do you register background services?
A: In `Program.cs` using `builder.Services.AddHostedService<>()`.
π MCQs
Q1. Which interface is used for background work in ASP.NET Core?
- IDisposable
- IStartupFilter
- IHostedService
- IWebHost
Q2. What method must you override in BackgroundService?
- Run
- Start
- Execute
- ExecuteAsync
Q3. How are background services registered?
- AddTransient
- AddScoped
- UseMiddleware
- AddHostedService<T>()
Q4. Do background services block HTTP requests?
- Yes
- Sometimes
- No
- Only in Development
Q5. What is passed to support graceful shutdown?
- TaskCompletionSource
- HttpContext
- ILogger
- CancellationToken
π‘ Bonus Insight
While BackgroundService
is best for continuous or polling tasks, consider using libraries like Hangfire, Quartz.NET, or Worker Services for complex scheduling or job persistence needs.
π PDF Download
Need a handy summary for your notes? Download this topic as a PDF!