Background task

De Banane Atomic
Version datée du 17 septembre 2024 à 13:43 par Nicolas (discussion | contributions) (Page créée avec « = Links = * [https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?tabs=visual-studio Background tasks with hosted services in ASP.NET Core] = Description = In ASP.NET Core, background tasks can be implemented as hosted services. = [https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?tabs=visual-studio#consuming-a-scoped-service-in-a-background-task Consuming a scoped service in a background task] = <filebox... »)
(diff) ← Version précédente | Voir la version actuelle (diff) | Version suivante → (diff)
Aller à la navigationAller à la recherche

Links

Description

In ASP.NET Core, background tasks can be implemented as hosted services.

Consuming a scoped service in a background task

MyBackgroundService.cs
public class MyBackgroundService(IServiceProvider services) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using (var scope = Services.CreateScope())
        {
            var scopedProcessingService = scope.ServiceProvider.GetRequiredService<IScopedProcessingService>();
            await scopedProcessingService.DoWork(stoppingToken);
        }
    }

    public override async Task StopAsync(CancellationToken stoppingToken)
    {
        await base.StopAsync(stoppingToken);
    }
}

Timed background tasks