in ASPNET Core, C#

Eseguire task in background utilizzando BackgroundService

Un metodo alternativo per la creazione di servizi eseguiti in background è l’utilizzo della classe BackgroundService, anzichè l’utilizzo dell’interfaccia IHostedService (vista nel post precedente). In pratica si procede ereditando la classe BackgroundService e facendo override del metodo asincrono ExecuteAsync . Scendendo nei dettagli si tratta di una classe astratta che implementa IHostedService, implementando i metodi StartAsync e StopAsync.

BackgroundService è presente all’interno del framework in Microsoft.Extensions.Hosting.

A differenza dell’ utilizzo di IHostedService è necessario implementare il metodo astratto ExecuteAsync:

public class MyService : BackgroundService
{
    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        throw new NotImplementedException();
    }
}
https://www.partech.nl/nl/publicaties/2021/04/practical-implementation—net-core-background-services#

A differenze dell’implementazione di StartAsync non è necessario eseguire l’attività separatamente e rischiare che l’applicazione web non venga fatta partire. E’ possibile eseguire l’attività del service in modalità asincrona con il classico async:

public class MyService: BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await Task.CompletedTask;
    }
}

Per la registrazione del service è necessario aggiungere il seguente codice all’interno del Program.cs

services.AddTransient<IHostedService, MyService>();