Links
Description
In ASP.NET Core, background tasks can be implemented as hosted services.
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>();
|
QueuedHostedService.cs
|
public class QueuedHostedService(IBackgroundTaskQueue taskQueue) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
var workItem = await TaskQueue.DequeueAsync(stoppingToken);
try
{
await workItem(stoppingToken);
}
catch (Exception ex)
{ }
}
}
}
|
Program.cs
|
services.AddHostedService<QueuedHostedService>();
services.AddSingleton<IBackgroundTaskQueue>(ctx =>
{
if (!int.TryParse(hostContext.Configuration["QueueCapacity"], out var queueCapacity))
queueCapacity = 100;
return new BackgroundTaskQueue(queueCapacity);
});
|