The IHostedService interface defines a contract for a background task. By implementing this interface in a concrete class, we can spawn workers in the background of our app and we don't interfere with it. These services have the life cycle of the ASP.NET app.
There is a special template in Visual Studio for creating a worker service:
This is a special kind of project that you can't use for serving web content. If you are curious, it uses the following declaration:
<ProjectSdk="Microsoft.NET.Sdk.Worker">
ASP.NET Core offers a convenience class, BackgroundService, from which you can inherit, instead of implementing IHostedService:
public class BackgroundHostedService : BackgroundService
{
protected override Task ExecuteAsync(CancellationToken
cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
//do something...