ASP.NET Core Interview Question #161

What is BackgroundService in ASP.NET Core?

Logging, Error Handling & Background Services Mid-Level Intermediate

Quick Interview Answer

BackgroundService is a base class for implementing long-running hosted services. A derived class overrides ExecuteAsync and performs work until the supplied cancellation token indicates that the host is shutting down.

Detailed Explanation

BackgroundService is a base class for implementing long-running hosted services. A derived class overrides ExecuteAsync and performs work until the supplied cancellation token indicates that the host is shutting down.

It is commonly used for queue consumers, scheduled polling, cleanup jobs, or other work that belongs in the application process but is not tied directly to one HTTP request.

Long-running background work must handle cancellation, exceptions, dependency lifetimes, and application shutdown correctly.

Code Example

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