Modern .NET applications frequently perform background processing. An API may receive incoming requests, a file-processing service may generate work items, or a message listener may continuously receive events from an external system. These operations often need to pass work from one part of an application to another without making the producer wait for every task to finish.

A common challenge appears when work is produced faster than it can be processed.

Consider an ASP.NET Core application that receives 500 customer events every second. Each event must be validated, processed, and saved to a database. However, the database processing service can handle only 200 events per second. If the application keeps accepting new events without controlling the workload, the number of pending items will continue increasing.

Eventually, this can cause high memory usage, longer processing delays, and application instability.

C# Channels provide an efficient way to manage communication between asynchronous producers and consumers. They allow one part of an application to write data while another part reads and processes it. Channels also support bounded capacity, asynchronous waiting, and multiple readers and writers.

In this article, we will explore how Channels work, implement producer-consumer processing in C#, control workloads when producers are faster than consumers, and apply practical patterns for background processing in .NET applications.

Understanding the Producer-Consumer Pattern

The producer-consumer pattern separates the creation of work from its execution.

A producer creates work items and places them into a shared communication mechanism. A consumer retrieves those items and processes them.

For example, consider an order-processing application.

The API receives an order request and creates an order-processing work item. Instead of performing every operation inside the HTTP request, the application places the item into a queue.

A background worker reads the item and performs the required processing.

The workflow looks like this:

Code
             Producer
                |
                |
        Creates Work Items
                |
                v
          Shared Channel
                |
                |
        Stores Pending Work
                |
                v
             Consumer
                |
                |
         Processes Items
                |
                v
           Database

This design separates request handling from background execution.

The producer does not need to know how the consumer processes the work. Similarly, the consumer does not need to know which controller or service created the item.

However, the shared queue must be managed carefully. If producers continuously generate work faster than consumers process it, pending items can accumulate.

This is where Channels become particularly useful.

What Are C# Channels?

System.Threading.Channels provides asynchronous producer-consumer communication for .NET applications.

A Channel contains two main interfaces:

  • ChannelWriter is used to add items.
  • ChannelReader is used to retrieve items.

The Channel class provides access to both sides.

Unlike a simple List or manually synchronized collection, Channels provide built-in coordination between asynchronous writers and readers.

For example, a producer can wait asynchronously when the channel is full. A consumer can wait asynchronously when no items are available.

This avoids unnecessary polling and reduces the need to implement custom synchronization logic.

The required namespace is:

C#
using System.Threading.Channels;

Channels support two important capacity models.

Unbounded Channels

An unbounded channel can continue accepting items without a configured capacity limit.

C#
var channel = Channel.CreateUnbounded<string>();

This is simple to use, but it does not provide automatic protection against continuously increasing workloads.

If producers are faster than consumers for an extended period, the channel can consume increasing amounts of memory.

Unbounded channels are appropriate only when the workload is known to be limited or another mechanism controls the number of pending items.

Bounded Channels

A bounded channel has a fixed capacity.

C#
var channel = Channel.CreateBounded<string>(100);

This channel can hold up to 100 pending items.

When the channel reaches its capacity, the behavior depends on the configured full mode.

A bounded channel is usually a better choice when the application needs predictable memory usage and controlled work admission.

Creating a Basic Producer-Consumer Channel

Let's begin with a simple example.

The producer generates customer processing jobs, while the consumer reads and processes them.

C#
using System.Threading.Channels;

var channel = Channel.CreateBounded<string>(10);

var producer = Task.Run(async () =>
{
    for (int i = 1; i <= 20; i++)
    {
        var job = $"Customer Job {i}";

        await channel.Writer.WriteAsync(job);

        Console.WriteLine($"Produced: {job}");
    }

    channel.Writer.Complete();
});

var consumer = Task.Run(async () =>
{
    await foreach (var job in channel.Reader.ReadAllAsync())
    {
        Console.WriteLine($"Processing: {job}");

        await Task.Delay(500);
    }
});

await Task.WhenAll(producer, consumer);

In this example, the channel has a capacity of 10.

The producer creates 20 jobs and writes them into the channel. The consumer reads each job and simulates processing by waiting for 500 milliseconds.

Because the producer can create jobs faster than the consumer processes them, the channel eventually becomes full.

When that happens, WriteAsync waits until space becomes available.

This is an important feature. Instead of allowing the application to keep increasing its pending workload, the producer experiences asynchronous backpressure.

Understanding WriteAsync

The WriteAsync method adds an item to the channel.

If the channel has available capacity, the operation completes successfully.

If the bounded channel is full and uses the Wait mode, the operation waits until a consumer removes an item.

This means the producer is automatically slowed down by the processing capacity of the consumer.

The application does not need to implement a separate delay or polling mechanism.

Understanding ReadAllAsync

ReadAllAsync provides an asynchronous stream of items from the channel.

The consumer waits for new items and processes them as they become available.

When the writer completes the channel and all pending items have been read, the asynchronous enumeration finishes.

This makes it convenient to implement background consumers using await foreach.

Understanding Bounded Channel Full Modes

One important configuration is BoundedChannelFullMode.

It determines what happens when the channel reaches its capacity.

C# Channels provide several full modes.

Full ModeBehaviorSuitable Scenario
WaitWriter waits until space becomes availableWork that must not be silently dropped
DropWriteIncoming item is droppedNew incoming data is less important
DropOldestOldest pending item is removedRecent state is more important
DropNewestNewest pending item already in the channel is removedOlder pending information is more important

The default behavior for a bounded channel is to wait when it becomes full.

You can configure a different mode when creating the channel.

For example:

C#
var options = new BoundedChannelOptions(100)
{
    FullMode = BoundedChannelFullMode.Wait,

    SingleReader = false,

    SingleWriter = false
};

var channel = Channel.CreateBounded<string>(options);

The SingleReader and SingleWriter properties describe whether the application has only one reader or writer.

Setting these properties accurately can allow the channel implementation to use optimizations.

Do not set them to true if multiple readers or writers may access the channel concurrently.

For payment processing, order creation, and other operations where every item matters, dropping work items is generally inappropriate. The Wait mode is often a better starting point.

Building a Reusable Background Job Queue

The previous example demonstrates how Channels work, but a real ASP.NET Core application needs a reusable queue that can be shared between controllers and background workers.

Let's create a simple work item queue.

First, define the queue interface:

C#
public interface IBackgroundTaskQueue
{
    ValueTask QueueAsync(
        Func<CancellationToken, ValueTask> workItem,
        CancellationToken cancellationToken);

    ValueTask<Func<CancellationToken, ValueTask>>
        DequeueAsync(CancellationToken cancellationToken);
}

The interface provides two operations.

QueueAsync adds a background operation to the channel.

DequeueAsync retrieves the next operation for processing.

Now implement the interface using a bounded channel:

C#
using System.Threading.Channels;

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

    public BackgroundTaskQueue(int capacity)
    {
        var options = new BoundedChannelOptions(capacity)
        {
            FullMode = BoundedChannelFullMode.Wait,
            SingleReader = false,
            SingleWriter = false
        };

        _channel = Channel.CreateBounded<
            Func<CancellationToken, ValueTask>>(options);
    }

    public async ValueTask QueueAsync(
        Func<CancellationToken, ValueTask> workItem,
        CancellationToken cancellationToken)
    {
        ArgumentNullException.ThrowIfNull(workItem);

        await _channel.Writer.WriteAsync(
            workItem,
            cancellationToken);
    }

    public async ValueTask<Func<CancellationToken, ValueTask>>
        DequeueAsync(CancellationToken cancellationToken)
    {
        return await _channel.Reader.ReadAsync(
            cancellationToken);
    }
}

This implementation uses a bounded channel with a configurable capacity.

When the queue becomes full, QueueAsync waits until a consumer creates space.

The queue can now be registered with dependency injection.

C#
builder.Services.AddSingleton<IBackgroundTaskQueue>(
    _ => new BackgroundTaskQueue(100));

A singleton is appropriate here because the application needs a shared queue instance for producers and consumers.

Processing Channel Items With a Background Service

ASP.NET Core provides BackgroundService for implementing long-running background operations.

Create a worker that reads queued jobs and executes them.

C#
public class QueueWorker : BackgroundService
{
    private readonly IBackgroundTaskQueue _queue;
    private readonly ILogger<QueueWorker> _logger;

    public QueueWorker(
        IBackgroundTaskQueue queue,
        ILogger<QueueWorker> logger)
    {
        _queue = queue;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            Func<CancellationToken, ValueTask> workItem;

            try
            {
                workItem = await _queue.DequeueAsync(
                    stoppingToken);
            }
            catch (OperationCanceledException)
                when (stoppingToken.IsCancellationRequested)
            {
                break;
            }

            try
            {
                await workItem(stoppingToken);
            }
            catch (OperationCanceledException)
                when (stoppingToken.IsCancellationRequested)
            {
                break;
            }
            catch (Exception exception)
            {
                _logger.LogError(
                    exception,
                    "Background work item failed.");
            }
        }
    }
}

Register the worker:

C#
builder.Services.AddHostedService<QueueWorker>();

This worker continuously retrieves and executes background operations.

It also catches individual job failures so that one failed operation does not automatically terminate the worker.

However, this example processes one job at a time. If processing is slower than incoming work, the queue may frequently reach its capacity.

Multiple consumers can improve throughput when the underlying operations can safely execute concurrently.

Using Multiple Consumers to Increase Throughput

A single consumer processes one item at a time.

If each operation takes 500 milliseconds, one consumer can complete approximately two operations per second under ideal conditions.

Multiple consumers can process independent work items simultaneously.

For example, the application can start four consumers:

C#
builder.Services.AddHostedService<QueueWorker>();

builder.Services.AddHostedService<QueueWorker>();

However, registering the same worker type multiple times is not a complete concurrency design by itself. It also requires correct worker configuration and consideration of the services used by each consumer.

Another approach is to create a worker that starts a fixed number of consumer tasks:

C#
public class ParallelQueueWorker : BackgroundService
{
    private readonly IBackgroundTaskQueue _queue;
    private readonly ILogger<ParallelQueueWorker> _logger;

    private const int WorkerCount = 4;

    public ParallelQueueWorker(
        IBackgroundTaskQueue queue,
        ILogger<ParallelQueueWorker> logger)
    {
        _queue = queue;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        var workers = Enumerable
            .Range(0, WorkerCount)
            .Select(_ => ProcessAsync(stoppingToken));

        await Task.WhenAll(workers);
    }

    private async Task ProcessAsync(
        CancellationToken cancellationToken)
    {
        while (!cancellationToken.IsCancellationRequested)
        {
            Func<CancellationToken, ValueTask> workItem;

            try
            {
                workItem = await _queue.DequeueAsync(
                    cancellationToken);
            }
            catch (OperationCanceledException)
                when (cancellationToken.IsCancellationRequested)
            {
                break;
            }

            try
            {
                await workItem(cancellationToken);
            }
            catch (OperationCanceledException)
                when (cancellationToken.IsCancellationRequested)
            {
                break;
            }
            catch (Exception exception)
            {
                _logger.LogError(
                    exception,
                    "A queued operation failed.");
            }
        }
    }
}

Now the application has four consumers reading from the same channel.

When one consumer processes a job, another consumer can retrieve a different job.

This increases the application's processing capacity when jobs are independent.

However, increasing consumer count does not always improve performance.

For example, if all consumers execute database operations against a database that is already overloaded, additional concurrency may make the situation worse.

Choose worker count according to database capacity, external service limits, CPU availability, and the nature of the workload.

Handling Producers That Are Faster Than Consumers

A bounded channel helps control the number of pending items.

Consider the following scenario:

  • Producer generates 500 work items per second.
  • Consumer processes 200 work items per second.
  • Channel capacity is 1,000 items.

The difference between production and processing rates is 300 items per second.

If this difference continues, the channel reaches its capacity after a short period.

With the Wait mode, producers begin waiting instead of adding unlimited work.

This is called backpressure.

Backpressure is important because it prevents an application from accepting work faster than its processing infrastructure can handle.

However, a bounded channel controls only the number of pending items in that particular channel. It does not automatically control work already accepted by other queues, external systems, or client requests.

The application still needs an appropriate admission policy.

For example, an API may need to reject new work with HTTP 429 or HTTP 503 when its processing capacity is exhausted, rather than allowing incoming HTTP requests to wait indefinitely.

Handling Queue Completion and Application Shutdown

Background workers need to stop gracefully when the application shuts down.

A channel writer can be completed using TryComplete or Complete.

For example:

C#
_channel.Writer.TryComplete();

After completion, no new items can be written.

Readers can continue processing items that were already accepted. Once the channel is completed and all pending items have been consumed, ReadAllAsync finishes.

For an application-managed queue, define a clear shutdown policy.

The application may need to:

  • Stop accepting new work.
  • Complete the channel.
  • Allow pending work to finish within a configured shutdown period.
  • Cancel remaining operations when the shutdown deadline is reached.
  • Log work items that could not be completed.

Remember that an in-memory channel is not durable.

If the application process crashes or the server restarts unexpectedly, pending items in the channel can be lost.

For operations that must survive application restarts, use a durable message broker or persistent job storage.

Monitoring Channel Performance

Using a bounded channel does not eliminate the need for monitoring.

A production application should track how quickly work enters and leaves the queue.

Useful measurements include:

MetricWhat It Indicates
Items producedIncoming workload
Items processedConsumer throughput
Queue depthNumber of pending items
Processing durationTime required to complete each item
Queue waiting timeHow long items remain pending
Failed itemsProcessing reliability
Rejected itemsWorkload exceeding admission limits

A channel does not provide a general public queue-depth property that can be used as a reliable production monitoring mechanism.

If queue depth is important, maintain it using carefully synchronized counters around successful writes and reads, or use another measurement mechanism designed for your workload.

The monitoring logic must account for dropped items, cancellation, failed writes, and completed reads so that the reported value remains meaningful.

Common Mistakes to Avoid

MistakeWhy It Causes ProblemsRecommended Approach
Using an unbounded channel for unlimited workPending items can consume increasing memoryUse bounded capacity
Setting SingleReader incorrectlyCan lead to incorrect concurrency assumptionsMatch settings to actual usage
Increasing consumer count without measuringCan overload databases or external servicesTune concurrency based on capacity
Ignoring cancellationWorkers may continue unnecessary operationsPropagate cancellation tokens
Allowing one failed job to terminate all processingRemaining jobs may stop being processedHandle failures at the individual job level
Assuming an in-memory channel is durablePending jobs can disappear after a restartUse persistent queues for critical work
Ignoring queue waiting timeDelayed processing may go unnoticedMonitor queue depth and processing latency
Dropping important work itemsBusiness operations may be lostUse the Wait mode or durable messaging

Summary

C# Channels provide an effective way to implement asynchronous producer-consumer communication in .NET applications. They allow producers to submit work while consumers process it independently, without requiring developers to build custom synchronization mechanisms.

Bounded channels are particularly useful when producers generate work faster than consumers can process it. By configuring an appropriate capacity and using the Wait mode, applications can apply backpressure and prevent pending work from growing without control.

For ASP.NET Core applications, Channels can be combined with BackgroundService to build reusable background processing pipelines. Multiple consumers can improve throughput when the workload supports parallel execution, but concurrency should be configured according to the capacity of dependent resources.

The most important consideration is choosing the right queue strategy for the work being processed. In-memory channels are useful for application-local communication, but they are not durable message queues. Critical operations that must survive application restarts should use persistent messaging infrastructure.

With appropriate capacity limits, cancellation handling, error management, and monitoring, Channels provide a practical foundation for reliable asynchronous processing in modern .NET applications.