ASP.NET Core Interview Question #162

What is IHostedService?

Logging, Error Handling & Background Services Mid-Level Intermediate

Quick Interview Answer

IHostedService defines the contract for services whose lifetime is managed by the .NET host. It contains StartAsync and StopAsync methods.

Detailed Explanation

IHostedService defines the contract for services whose lifetime is managed by the .NET host. It contains StartAsync and StopAsync methods.

StartAsync is called when the host starts, and StopAsync is called during graceful shutdown. BackgroundService is a convenient abstract implementation of IHostedService for services that mainly need a long-running ExecuteAsync method.

Use IHostedService directly when explicit startup and shutdown behavior is more appropriate than a continuous worker loop.

Code Example

public class CacheWarmupService : IHostedService
{
    public Task StartAsync(CancellationToken cancellationToken)
    {
        // Perform startup work.
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        // Perform shutdown work.
        return Task.CompletedTask;
    }
}