Skip to main content

Lesson 4 of 8

BackgroundService & Channel-Based Task Queue

Heavy operations (email sending, image processing, PDF generation) should not block HTTP request threads. Channel<T> is a thread-safe, in-process message queue. Controller enqueues work, BackgroundService processes it asynchronously - HTTP response returns immediately.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Channel Queue + BackgroundService Worker

Channel Queue + BackgroundService Worker
using System.Threading.Channels;
using Microsoft.Extensions.Hosting;

// ━━ Task queue - wrapper around Channel<T> ━━
public interface IBackgroundTaskQueue
{
    ValueTask EnqueueAsync(Func<CancellationToken, Task> workItem, CancellationToken ct = default);
    ValueTask<Func<CancellationToken, Task>> DequeueAsync(CancellationToken ct);
}

public class BackgroundTaskQueue : IBackgroundTaskQueue
{
    private readonly Channel<Func<CancellationToken, Task>> _channel;

    public BackgroundTaskQueue(int capacity = 100)
    {
        // BoundedChannel: backpressure - EnqueueAsync blocks when queue is full
        _channel = Channel.CreateBounded<Func<CancellationToken, Task>>(
            new BoundedChannelOptions(capacity)
            {
                FullMode = BoundedChannelFullMode.Wait, // producer waits (no drops)
                SingleReader = true,                     // optimization for single consumer
                SingleWriter = false,                    // multiple HTTP threads can enqueue
            });
    }

    public ValueTask EnqueueAsync(Func<CancellationToken, Task> workItem, CancellationToken ct = default) =>
        _channel.Writer.WriteAsync(workItem, ct);

    public ValueTask<Func<CancellationToken, Task>> DequeueAsync(CancellationToken ct) =>
        _channel.Reader.ReadAsync(ct);
}

// ━━ BackgroundService worker - runs for app lifetime ━━
public class QueuedHostedService(
    IBackgroundTaskQueue taskQueue,
    ILogger<QueuedHostedService> logger,
    IServiceProvider services) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        logger.LogInformation("BackgroundService started");

        await foreach (var workItem in GetWorkItemsAsync(stoppingToken))
        {
            try
            {
                // Each work item gets its own DI scope (for scoped services like DbContext)
                using var scope = services.CreateScope();
                await workItem(stoppingToken);
            }
            catch (OperationCanceledException) { throw; } // re-throw shutdown signal
            catch (Exception ex)
            {
                logger.LogError(ex, "BackgroundService error processing work item");
                // Continue processing - don't crash the service
            }
        }
    }

    private async IAsyncEnumerable<Func<CancellationToken, Task>> GetWorkItemsAsync(
        [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken ct)
    {
        while (!ct.IsCancellationRequested)
            yield return await taskQueue.DequeueAsync(ct);
    }
}

// ━━ Registration ━━
builder.Services.AddSingleton<IBackgroundTaskQueue, BackgroundTaskQueue>();
builder.Services.AddHostedService<QueuedHostedService>();

// ━━ Controller - fire and forget ━━
[HttpPost("{id}/generate-report")]
public async Task<IActionResult> GenerateReport(Guid id, [FromServices] IBackgroundTaskQueue queue)
{
    var userId = User.FindFirstValue(ClaimTypes.NameIdentifier)!;

    // Enqueue - returns immediately to client
    await queue.EnqueueAsync(async ct =>
    {
        // Runs in background - has access to captured variables
        await Task.Delay(5000, ct); // simulate PDF generation
        Console.WriteLine($"Report generated for order {id}, user {userId}");
    });

    return Accepted(new { message = "Report generation started. You'll receive an email when ready." });
}

Tip

Tip

Practice BackgroundService ChannelBased Task Queue in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of BackgroundService ChannelBased Task Queue from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with BackgroundService ChannelBased Task Queue is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done