IConfiguration vs IOptions NET
Synchronous and Asynchronous in .NET Core
Model Binding and Validation in ASP.NET Core
ControllerBase vs Controller in ASP.NET Core
ConfigureServices and Configure methods
IHostedService interface in .NET Core
ASP.NET Core request processing
| ConfigureServices and Configure methods | ASP.NET Core request processing | |
BackgroundService and IHostedService in ASP.NET Core |
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:
IHostedService defines two methods:
Task StartAsync(CancellationToken cancellationToken); Task StopAsync(CancellationToken cancellationToken);
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();
}
}
In Program.cs (or Startup.ConfigureServices in older templates):
builder.Services.AddHostedService<TimedHostedService>();
That’s it — the host will:
TimedHostedService at startup.StartAsync automatically.StopAsync on shutdown.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.
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).
| 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 |
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);
}
}
}
builder.Services.AddHostedService<MyWorkerService>();
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 | ASP.NET Core request processing | |