ASP.NET Core Web API Interview Question #165

What is IHostedService?

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

Quick Interview Answer

IHostedService defines StartAsync and StopAsync for services whose lifecycle is controlled by the ASP.NET Core host. BackgroundService is a convenience implementation for services centered around a long-running ExecuteAsync loop.

Detailed Explanation

IHostedService defines StartAsync and StopAsync for services whose lifecycle is controlled by the ASP.NET Core host. BackgroundService is a convenience implementation for services centered around a long-running ExecuteAsync loop.

Hosted services should start promptly and respond correctly to shutdown cancellation so application startup and termination are not unnecessarily delayed.

Code Example

public sealed class WarmupService : IHostedService
{
    public Task StartAsync(CancellationToken token)
        => WarmCacheAsync(token);

    public Task StopAsync(CancellationToken token)
        => Task.CompletedTask;
}