| ConfigureServices and Configure methods :👈 | 👉:IServiceCollection and IApplicationBuilder |
BackgroundService and IHostedService in ASP.NET Core |
🧩 What is IHostedService?
In ASP.NET Core, IHostedService is an interface that lets you run background tasks as part of your application’s lifetime. It’s part of the generic host infrastructure and is ideal for:
- Running long-lived background processes (e.g., polling, scheduled jobs, queue processing).
- Starting tasks when the app starts and stopping them gracefully when the app shuts down.
- Integrating background work into the dependency injection (DI) and lifecycle management of ASP.NET Core.
🔍 How It Works
IHostedService defines two methods:
Task StartAsync(CancellationToken cancellationToken);
Task StopAsync(CancellationToken cancellationToken);
StartAsync
- Called once when the host starts.
- Use it to start timers, queues, or background loops.
- Should return quickly — don’t block startup.
StopAsync
- Called when the host is shutting down.
- Use it to stop timers, cancel loops, and clean up resources.
- Should respect the cancellation token for graceful shutdown.
🛠 Example: Implementing IHostedService
Here’s a simple background service that logs a message every 5 seconds.
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
public class TimedHostedService : IHostedService, IDisposable
{
private readonly ILogger<TimedHostedService> _logger;
private Timer _timer;
public TimedHostedService(ILogger<TimedHostedService> logger)
{
_logger = logger;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Timed Hosted Service starting.");
// Run DoWork every 5 seconds
_timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
return Task.CompletedTask;
}
private void DoWork(object state)
{
_logger.LogInformation("Timed Hosted Service is working at: {time}", DateTimeOffset.Now);
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Timed Hosted Service stopping.");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
📦 Registering the Hosted Service
In Program.cs (or Startup.ConfigureServices in older templates):
builder.Services.AddHostedService<TimedHostedService>();
That’s it — the host will:
- Create an instance of
TimedHostedServiceat startup. - Call
StartAsyncautomatically. - Call
StopAsyncon shutdown.
🚀 When to Use IHostedService
- Polling APIs at intervals.
- Processing background queues (e.g., RabbitMQ, Azure Service Bus).
- Scheduled jobs without needing an external scheduler.
- Long-running listeners (e.g., file watchers, socket listeners).
💡 Pro Tip
If your background task runs continuously or needs async loops, consider inheriting from BackgroundService (an abstract base class that implements IHostedService for you) — it simplifies the pattern by letting you just override ExecuteAsync.
🧠 What is BackgroundService?
BackgroundService is an abstract base class that implements IHostedService. It simplifies the creation of long-running background tasks by providing a method called ExecuteAsync(CancellationToken).
🔗 Relationship Between Them
| Feature | IHostedService | BackgroundService |
|---|---|---|
| Type | Interface | Abstract class |
| Methods | StartAsync, StopAsync | ExecuteAsync (wraps Start/Stop) |
| Ease of Use | Manual implementation required | Simplified with async loop |
| Cancellation Support | Manual | Built-in via CancellationToken |
🛠 Example: Using BackgroundService
public class MyWorkerService : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
Console.WriteLine($"Running at: {DateTime.Now}");
await Task.Delay(5000, stoppingToken);
}
}
}
📦 Registering the Service
builder.Services.AddHostedService<MyWorkerService>();
✅ Summary
Use IHostedService for full control over background task lifecycle. Use BackgroundService when you want a cleaner, simpler way to run continuous or periodic background tasks.
| ConfigureServices and Configure methods :👈 | 👉:IServiceCollection and IApplicationBuilder |