.NET Architecture & System Design Interview Question #49

What is a background service in ASP.NET Core?

Caching, CDN, Queues & Asynchronous Processing Junior Beginner

Quick Interview Answer

ASP.NET Core supports long-running hosted work through IHostedService and BackgroundService. These are useful for tasks such as polling, scheduled maintenance, or consuming messages when the work belongs inside the application host.

Detailed Explanation

ASP.NET Core supports long-running hosted work through IHostedService and BackgroundService. These are useful for tasks such as polling, scheduled maintenance, or consuming messages when the work belongs inside the application host.

A background service must handle cancellation, exceptions, dependency lifetimes, and graceful shutdown correctly. Critical durable jobs should not rely only on in-memory work that disappears when the process terminates.

Code Example

public class QueueWorker : BackgroundService
{
    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
            await ProcessNextAsync(stoppingToken);
    }
}