⚙️ C# / .NET Intermediate

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.