ASP.NET Core Web API Interview Question #164

What is a BackgroundService in ASP.NET Core?

Testing, HttpClient, Integration Testing, Background Services & Deployment Senior Advanced

Quick Interview Answer

BackgroundService is a base class for long-running hosted work managed by the application's host. A derived class implements ExecuteAsync and observes the supplied stopping token.

Detailed Explanation

BackgroundService is a base class for long-running hosted work managed by the application's host. A derived class implements ExecuteAsync and observes the supplied stopping token.

It is useful for lightweight in-process background tasks, but durable business jobs may require a persistent queue or external worker architecture so work is not lost when the web process restarts.

Code Example

public sealed class CleanupWorker : BackgroundService
{
    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            await RunCleanupAsync(stoppingToken);
            await Task.Delay(TimeSpan.FromHours(1), stoppingToken);
        }
    }
}