Skip to main content

Background Services

IHostedService

public class EmailSenderService : IHostedService
{
public Task StartAsync(CancellationToken cancellationToken)
{
// Start background work
return Task.CompletedTask;
}

public Task StopAsync(CancellationToken cancellationToken)
{
// Stop background work
return Task.CompletedTask;
}
}

builder.Services.AddHostedService<EmailSenderService>();

BackgroundService

public class DataCleanupService : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
// Do work
await Task.Delay(TimeSpan.FromHours(1), stoppingToken);
}
}
}

Channels (Producer-Consumer)

public class QueueService
{
private readonly Channel<string> _channel = Channel.CreateUnbounded<string>();

public async Task EnqueueAsync(string item)
{
await _channel.Writer.WriteAsync(item);
}

public IAsyncEnumerable<string> DequeueAllAsync(CancellationToken ct)
{
return _channel.Reader.ReadAllAsync(ct);
}
}