What is a hosted service in ASP.NET Core?
Answer
A hosted service is a background long-running service that runs alongside your ASP.NET Core application, managed by the host. Implements IHostedService or inherits from BackgroundService (simpler). BackgroundService pattern: public class MyBackgroundJob : BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { await DoWorkAsync(); await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken); } } }. Register: builder.Services.AddHostedService<MyBackgroundJob>();. Use cases: polling an external service, processing a message queue (RabbitMQ consumer, Azure Service Bus), scheduled tasks (replace cron jobs), sending scheduled emails, cache warming. For CPU-intensive work, offload to a dedicated background queue (IBackgroundTaskQueue pattern). Quartz.NET is a popular library for complex scheduling scenarios (cron expressions). Worker Service template creates a standalone background process without the HTTP server overhead.
Previous
What is middleware authentication vs authorization in ASP.NET Core?
Next
What is the difference between AddSingleton, AddScoped, and AddTransient?
More C# / .NET Questions
View all →- Intermediate What is ASP.NET Core and how does it differ from ASP.NET Framework?
- Intermediate What is middleware in ASP.NET Core?
- Intermediate What is dependency injection in ASP.NET Core?
- Intermediate What is Entity Framework Core?
- Intermediate What is the difference between eager, lazy, and explicit loading in EF Core?