« Background task » : différence entre les versions
De Banane Atomic
Aller à la navigationAller à la recherche
(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... ») |
|||
Ligne 13 : | Ligne 13 : | ||
using (var scope = Services.CreateScope()) | using (var scope = Services.CreateScope()) | ||
{ | { | ||
var | var scopedService = scope.ServiceProvider.GetRequiredService<IMyScopedService>(); | ||
await | await scopedService.DoWork(stoppingToken); | ||
} | } | ||
} | } | ||
Ligne 23 : | Ligne 23 : | ||
} | } | ||
} | } | ||
</filebox> | |||
<filebox fn='Program.cs'> | |||
services.AddHostedService<MyBackgroundService>(); | |||
services.AddScoped<IMyScopedService, MyScopedService>(); | |||
</filebox> | </filebox> | ||
= [https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?tabs=visual-studio#timed-background-tasks Timed background tasks] = | = [https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?tabs=visual-studio#timed-background-tasks Timed background tasks] = |
Version du 17 septembre 2024 à 13:44
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 scopedService = scope.ServiceProvider.GetRequiredService<IMyScopedService>(); await scopedService.DoWork(stoppingToken); } } public override async Task StopAsync(CancellationToken stoppingToken) { await base.StopAsync(stoppingToken); } } |
Program.cs |
services.AddHostedService<MyBackgroundService>(); services.AddScoped<IMyScopedService, MyScopedService>(); |