Background workers are made to operate continually. Throughout the day, they could handle hundreds of communications, synchronise information, issue notifications, produce reports, or carry out planned actions. A long-running worker can be active for days or weeks without restarting, in contrast to short-lived programs. Because of this, memory management is very crucial. A little memory leak that is difficult to detect during a brief test might progressively raise memory use until the program slows down, starts collecting too much trash, or finally raises an OutOfMemoryException.

The problem is that while the Garbage Collector (GC) in.NET offers automated memory management, it is unable to stop all memory leaks. When references to objects that are no longer valuable to the program are still available, they may stay in memory. This article describes how to find memory leaks in long-running.NET workers, utilise built-in diagnostic tools to look into memory expansion, comprehend frequent causes, and address memory retention issues without adding needless performance cost.

Understanding Memory Leaks in .NET Background Workers
The .NET Garbage Collector automatically reclaims managed memory when objects are no longer reachable through application references.

For example, consider the following method:
public void ProcessOrder()
{
    var order = new Order
    {
        Id = 1001,
        CustomerName = "John"
    };

    Console.WriteLine(order.CustomerName);
}

When ProcessOrder completes, the local order variable is no longer accessible through the method. If nothing else references the object, the Garbage Collector can eventually reclaim its memory.

However, consider a background worker that stores every processed order in a static collection:
public static class OrderStore
{
    public static List<Order> ProcessedOrders { get; } = new();
}


Every time an order is processed, the worker adds it to the collection:
OrderStore.ProcessedOrders.Add(order);

The collection continues holding references to previously processed orders. Even though the application no longer needs those orders, the Garbage Collector cannot reclaim them.

This is a managed memory leak.

In a long-running worker, the problem becomes more serious because the collection can continue growing with every execution.

Memory Growth Does Not Always Mean a Memory Leak

Before investigating a worker, understand the difference between memory allocation, memory retention, and memory leaks. A worker may allocate temporary objects while processing records. The Garbage Collector reclaims those objects when they are no longer reachable. However, the process may not immediately return all memory to the operating system after garbage collection. The runtime can retain committed heap memory for future allocations.

Therefore, a high process working set does not automatically indicate a memory leak.

Monitor several measurements together:

Memory measurement

What it indicates

Managed heap size

Memory occupied by managed objects

GC committed memory

Memory committed for managed heap usage

Process working set

Physical memory currently associated with the process

Allocation rate

How quickly the application creates new objects

Gen 2 collection count

Number of full-generation garbage collections

Large Object Heap size

Memory occupied by large managed objects

A memory leak becomes more likely when managed heap usage continues growing after garbage collection, particularly when the same types of objects accumulate over time.

Common Causes of Memory Leaks in Background Workers
Memory leaks in background services often come from application design rather than the Garbage Collector itself.

Unbounded Collections
One of the simplest mistakes is keeping processed records in a collection without removing them.

Consider this worker:
public class OrderWorker : BackgroundService
{
    private readonly List<Order> _processedOrders = new();

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var orders = await GetPendingOrdersAsync(
                stoppingToken);

            _processedOrders.AddRange(orders);

            await Task.Delay(
                TimeSpan.FromSeconds(10),
                stoppingToken);
        }
    }

    private static Task<List<Order>> GetPendingOrdersAsync(
        CancellationToken cancellationToken)
    {
        return Task.FromResult(new List<Order>());
    }
}


The list belongs to the worker instance and remains available for as long as the worker exists.

If the worker processes thousands of orders, the collection continues growing.

If the application only needs to process the current batch, keep the data local to the processing operation instead:
private async Task ProcessOrdersAsync(
    CancellationToken cancellationToken)
{
    var orders = await GetPendingOrdersAsync(
        cancellationToken);

    foreach (var order in orders)
    {
        cancellationToken.ThrowIfCancellationRequested();

        await ProcessOrderAsync(
            order,
            cancellationToken);
    }
}


The collection becomes eligible for garbage collection after the operation finishes, provided no other references remain.

If caching is genuinely required, define a maximum size, expiration policy, and eviction strategy.

Event Handlers That Are Never Unsubscribed
Event subscriptions can unintentionally keep objects alive.

Consider a service that subscribes to an event published by a long-lived object:
public class NotificationWorker
{
    private readonly NotificationPublisher _publisher;

    public NotificationWorker(
        NotificationPublisher publisher)
    {
        _publisher = publisher;

        _publisher.NotificationReceived +=
            OnNotificationReceived;
    }

    private void OnNotificationReceived(
        object? sender,
        EventArgs e)
    {
        Console.WriteLine("Notification received");
    }

}

The publisher holds a reference to the event handler. That handler can hold a reference to the NotificationWorker instance.
Even if the application no longer needs the worker, the event subscription may prevent it from being collected.

Unsubscribe when the subscription is no longer required:
public class NotificationWorker : IDisposable
{
    private readonly NotificationPublisher _publisher;

    public NotificationWorker(
        NotificationPublisher publisher)
    {
        _publisher = publisher;

        _publisher.NotificationReceived +=
            OnNotificationReceived;
    }

    private void OnNotificationReceived(
        object? sender,
        EventArgs e)
    {
        Console.WriteLine("Notification received");
    }

    public void Dispose()
    {
        _publisher.NotificationReceived -=
            OnNotificationReceived;
    }
}


For hosted services, perform the cleanup as part of the worker's lifecycle or implement the appropriate disposal pattern.

Timers and Callbacks Retaining Objects

Timers can also keep references alive through their callbacks.
If a timer callback captures a worker or another service, the timer may keep that object reachable.

Always dispose timers when they are no longer needed.
For recurring asynchronous operations, PeriodicTimer is often easier to manage inside BackgroundService because it participates naturally in the worker's cancellation flow.
protected override async Task ExecuteAsync(
    CancellationToken stoppingToken)
{
    using var timer = new PeriodicTimer(
        TimeSpan.FromSeconds(30));

    while (await timer.WaitForNextTickAsync(
        stoppingToken))
    {
        await ProcessBatchAsync(stoppingToken);
    }
}


The using statement ensures that the timer is disposed when execution exits.

Incorrect Management of Scoped Services

BackgroundService is typically registered as a singleton. Injecting scoped services directly into a singleton can cause lifetime problems.
For example, an Entity Framework Core DbContext registered as scoped should not be held by a singleton worker for its entire lifetime.

Instead, create a scope for each processing batch:
public sealed class OrderWorker : BackgroundService
{
    private readonly IServiceScopeFactory _scopeFactory;

    public OrderWorker(
        IServiceScopeFactory scopeFactory)
    {
        _scopeFactory = scopeFactory;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            await using var scope =
                _scopeFactory.CreateAsyncScope();

            var processor = scope.ServiceProvider
                .GetRequiredService<IOrderProcessor>();

            await processor.ProcessAsync(stoppingToken);

            await Task.Delay(
                TimeSpan.FromSeconds(10),
                stoppingToken);
        }
    }
}


Each iteration gets a new scope. Scoped dependencies are disposed when the scope is disposed.
This prevents the worker from retaining database contexts and other scoped objects unnecessarily.

Unbounded Queues and Channels

A background worker may receive messages faster than it can process them. If the application uses an unbounded queue or channel, pending messages can accumulate in memory.

For example:
var channel = Channel.CreateUnbounded<Order>();

If producers continuously add orders while the consumer processes them slowly, memory consumption can grow without a fixed limit.

Use a bounded channel when the application needs backpressure:

var channel = Channel.CreateBounded<Order>(
    new BoundedChannelOptions(1000)
    {
        FullMode = BoundedChannelFullMode.Wait,
        SingleReader = true,
        SingleWriter = false
    });


The channel now has a maximum capacity of 1,000 items. When it becomes full, producers must wait for available space rather than adding unlimited items. Choose the capacity according to the expected workload and the size of each item. A bounded queue prevents unlimited memory growth, but it does not replace durable messaging when messages must survive process restarts.

Monitor Memory Usage With dotnet-counters
Before collecting memory dumps, confirm whether the worker is actually experiencing sustained memory growth.

The dotnet-counters tool provides runtime performance counters that help identify memory-related problems.

Install it using:
dotnet tool install --global dotnet-counters

Find the running worker process:
dotnet-counters ps

Start monitoring the process:
dotnet-counters monitor --process-id 12345

Replace 12345 with the actual process ID.
For a focused investigation, monitor the System.Runtime provider.

Pay attention to the following metrics:

  • GC heap size: Shows the size of the managed heap.
  • Allocation rate: Indicates how quickly objects are allocated.
  • Gen 0, Gen 1, and Gen 2 collection counts: Show garbage collection activity.
  • LOH size: Shows memory used by large managed objects.
  • GC committed bytes: Shows committed managed heap memory.
  • Working set: Shows the process's current physical memory usage.
  • Time in GC: Helps identify whether garbage collection is consuming significant execution time.

Metric names and available counters can vary by runtime and diagnostic tool version.

What Should You Look For?
Suppose a worker starts with a managed heap of approximately 100 MB. After several hours, the heap reaches 300 MB and continues growing.
This alone does not prove a leak.

Observe what happens after Gen 2 garbage collections. If the managed heap consistently returns to a similar level, the application may simply be experiencing temporary allocation pressure.

However, if the heap continues increasing after collections, investigate which objects remain reachable.

A useful investigation compares memory usage during different stages:

Observation

Possible explanation

High allocation rate, stable post-GC heap

Temporary allocation pressure

Continuously growing post-GC heap

Possible managed memory leak

High working set, stable managed heap

Native memory, runtime reservations, or other process memory

Growing LOH

Large arrays, buffers, or strings being retained

Growing queue length and heap

Producers are faster than consumers

Increasing Gen 2 collections and GC time

Sustained memory pressure

The objective is to identify a consistent pattern rather than reacting to a single memory measurement.

Capture a Memory Dump With dotnet-dump
When counters suggest that objects are being retained, capture a memory dump for deeper investigation.

Install the tool:

dotnet tool install --global dotnet-dump

Collect a dump from the running worker:
dotnet-dump collect --process-id 12345

A heap-containing dump can consume substantial disk space and may temporarily affect the application. Collect it during an appropriate diagnostic window and protect the resulting file because memory dumps can contain sensitive application data.

For better comparison, collect two dumps at different points while the worker is running under similar workload conditions.

For example:

  • Capture the first dump after the worker has been running for a short period.
  • Allow it to process a representative workload.
  • Capture another dump after memory usage has increased.

Comparing the two helps identify which object types are accumulating.

Analyze the Memory Dump
Open the collected dump:
dotnet-dump analyze dumpfile.dmp

The analysis environment supports SOS commands for examining the managed heap.

Start by inspecting the heap statistics:
dumpheap -stat

This command displays the number and total size of objects grouped by type.

For example, the output might show:
Count       TotalSize       Class Name

150000      12000000        System.String
50000       10000000        MyApp.Models.Order
25000        8000000        System.Byte[]
1000         2000000        System.Object[]


If the number of Order objects increases significantly between dumps, investigate where those objects are being stored.

The next step is to identify why an object is still reachable.

Use gcroot with an object address:
gcroot 00007f6ad09421f8

This command displays the reference paths that keep the object alive.
For example, the output may reveal that an Order object is referenced by a List stored in a long-lived OrderCache service.

That gives you a starting point for finding the corresponding application code.

Useful commands include:

Command

Purpose

dumpheap -stat

Shows object counts and memory usage by type

dumpheap -type MyApp.Order

Finds objects matching a type name

gcroot

Shows references keeping an object alive

dumpasync

Inspects asynchronous state machines

dumpgen

Examines objects in a specific GC generation

threadpool

Displays thread pool information

Use the dump to investigate object retention rather than assuming that the largest object is automatically the source of the leak.

Investigate Large Object Heap Growth
The Large Object Heap (LOH) is used for large managed objects, including sufficiently large arrays and strings.

For example, a worker that downloads files into byte arrays or generates large reports may create many large objects.

Consider this implementation:
public async Task ProcessFileAsync(
    string filePath,
    CancellationToken cancellationToken)
{
    var fileBytes = await File.ReadAllBytesAsync(
        filePath,
        cancellationToken);

    await UploadFileAsync(
        fileBytes,
        cancellationToken);
}

This approach loads the entire file into memory.

If multiple jobs run concurrently, several large byte arrays may remain alive at the same time.

For large files, streaming is often more appropriate:
public async Task ProcessFileAsync(
    string filePath,
    CancellationToken cancellationToken)
{
    await using var source = File.OpenRead(filePath);

    await UploadStreamAsync(
        source,
        cancellationToken);
}


The streaming approach avoids loading the entire file into one byte array.

However, streaming alone does not guarantee low memory usage. The upload implementation must also avoid buffering the complete stream internally.

For large workloads, review buffer sizes, concurrency limits, and object lifetimes together.

Investigate Native Memory and Unmanaged Resources
Not every memory problem appears in the managed heap.
A .NET worker may use native libraries, unmanaged buffers, file handles, sockets, or other operating system resources.

If the process working set grows while managed heap measurements remain relatively stable, investigate memory outside the managed heap.

Review code that uses:

  • Native interop.
  • Unmanaged memory allocation.
  • Image and video processing libraries.
  • Native database drivers.
  • Large file buffers.
  • Third-party libraries that manage native resources.

Objects that own unmanaged resources should implement an appropriate disposal mechanism, typically IDisposable or IAsyncDisposable.

For example:
await using var stream = new FileStream(
    filePath,
    FileMode.Open,
    FileAccess.Read,
    FileShare.Read);

Disposing managed wrappers helps release the underlying operating system resources.

For native allocations made directly through interop, ensure that the matching native release function is called. The Garbage Collector cannot automatically determine when arbitrary unmanaged allocations are no longer needed.

Best Practices for Preventing Memory Leaks

A reliable background worker should be designed to control object lifetimes and resource consumption from the beginning.

  • Avoid storing processed records in static collections unless there is a clear retention policy.
  • Use bounded channels and queues when producers can outpace consumers.
  • Dispose timers, streams, database connections, and other disposable resources correctly.
  • Create dependency injection scopes for scoped services used by long-running workers.
  • Unsubscribe event handlers when their subscriptions are no longer required.
  • Reuse HttpClient through IHttpClientFactory or an appropriately managed long-lived instance.
  • Stream large files instead of loading entire files into memory.
  • Limit the number of concurrently processed jobs.
  • Monitor managed heap size, allocation rate, and process working set.
  • Capture memory dumps when counters indicate sustained object retention.
  • Compare heap snapshots under similar workloads.
  • Include memory monitoring in long-running load tests.

Also avoid calling GC.Collect repeatedly as a way to fix memory growth. Forcing garbage collection does not remove objects that are still referenced. It can also introduce unnecessary pauses and hide the real problem.

Common Mistakes During Memory Leak Investigation
Some diagnostic approaches can lead to incorrect conclusions.

  • Treating process working set as the same measurement as managed heap size.
  • Assuming every increase in memory usage indicates a memory leak.
  • Restarting the worker repeatedly without collecting diagnostic information.
  • Calling GC.Collect to force memory cleanup.
  • Collecting only one memory dump without comparing it with another snapshot.
  • Ignoring event subscriptions and static references.
  • Forgetting to dispose scoped services and unmanaged resources.
  • Increasing container memory limits without identifying the source of growth.
  • Ignoring unbounded queues and concurrent processing.
  • Capturing production memory dumps without considering sensitive information.

A useful investigation should connect memory growth to actual object references or unmanaged allocations.

Summary

Memory leaks in long-running .NET workers can gradually affect performance, increase garbage collection activity, and eventually cause application failures. Start by monitoring runtime counters with dotnet-counters. Compare managed heap usage, allocation rate, GC activity, large object heap growth, and process working set to determine whether memory is genuinely being retained.

When the measurements indicate a possible leak, capture memory dumps with dotnet-dump. Use dumpheap to identify growing object types and gcroot to discover why those objects remain reachable. Pay particular attention to static collections, event subscriptions, timers, scoped service lifetimes, unbounded queues, large buffers, and unmanaged resources. The most effective approach is to combine correct resource management with continuous monitoring and repeatable diagnostics. A background worker should be able to process work continuously without allowing unnecessary objects and resources to accumulate throughout its lifetime.

HostForLIFE.eu ASP.NET Core 11.0 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.