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>();
|
ItemQueue
|
public class ItemQueue<T> : IItemQueue
{
private readonly ConcurrentQueue<T> queue = new();
public void Enqueue(T item) => queue.Enqueue(item);
public bool TryDequeue(out T item) => queue.TryDequeue(out item);
}
public interface IItemQueue<T>
{
void Enqueue(T item);
bool TryDequeue(out T item);
}
|
QueuedHostedService.cs
|
public class QueuedHostedService(IItemQueue itemQueue) : BackgroundService
{
public IItemQueue ItemQueue { get; } = itemQueue;
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(1000, stoppingToken);
if (ItemQueue.TryDequeueAsync(out var item))
{
await DoAsync(item);
}
}
}
}
|
Program.cs
|
services.AddHostedService<QueuedHostedService>();
services.AddSingleton<IItemQueue<MyItem>, ItemQueue<MyItem>>();
|