In ASP.NET Core, background services run tasks outside the scope of a user's request. These are useful for scenarios like data processing, sending notifications, or periodic cleanup tasks.
IHostedService
interface for managing background tasks.BackgroundService
, a base class to simplify creating hosted services.Follow these steps to create and use a background service:
// Services/ExampleBackgroundService.cs
using Microsoft.Extensions.Hosting;
public class ExampleBackgroundService : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
Console.WriteLine("Background service is running...");
await Task.Delay(5000, stoppingToken); // Simulate periodic work
}
}
}
The ExecuteAsync
method runs continuously, performing work at regular intervals.
// Program.cs
var builder = WebApplication.CreateBuilder(args);
// Add the background service to the dependency injection container
builder.Services.AddHostedService<ExampleBackgroundService>();
var app = builder.Build();
app.MapGet("/", () => "Welcome to Background Services Demo!");
app.Run();
Use the AddHostedService
method to register the service.
When you run the application, the background service starts running alongside the web server. Observe the console output:
Background service is running...
Background service is running...
The message appears every 5 seconds as the service executes.
IHostedService
Interface
// Services/CustomHostedService.cs
using Microsoft.Extensions.Hosting;
public class CustomHostedService : IHostedService
{
private Timer _timer;
public Task StartAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Hosted service starting...");
_timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
return Task.CompletedTask;
}
private void DoWork(object state)
{
Console.WriteLine("Hosted service task running...");
}
public Task StopAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Hosted service stopping...");
_timer?.Dispose();
return Task.CompletedTask;
}
}
The StartAsync
method initializes the service, while StopAsync
cleans up resources.
// Program.cs
builder.Services.AddHostedService<CustomHostedService>();
Add the hosted service to the dependency injection container.