C# – Agregar BackgroundService a un proyecto .net Core

Agregue una clase “MainBackgroundService

   public class MainBackgroundService

    {

    }

 

Agregue referencia a “Microsoft.Extensions.Hosting

using Microsoft.Extensions.Hosting;

 

Agregue herencia a la clase “BackgroundService

   public class MainBackgroundService : BackgroundService

    {

    }

 

Agregue el método sobrecargado “ExecuteAsync

       protected async override Task ExecuteAsync(CancellationToken stoppingToken)

        {

            while (!stoppingToken.IsCancellationRequested)

            {

                //Su codigo aqui

                await Task.Delay(10000, stoppingToken);

            }

        }

 

Registre el “MainBackgroundService” en el “Startup” en “ConfigureServices(IServiceCollection services)

       services.AddHostedService<BackgroundService>();

 

Probado en: .net Core 2.0