A .NET application can run perfectly during development and still develop serious memory problems after running continuously in production.

An API may handle thousands of requests, a background worker may process messages throughout the day, or a scheduled service may execute jobs every few minutes. Everything appears normal initially, but memory consumption gradually increases.

After several hours or days, the application starts responding slowly. Garbage collection becomes more frequent, CPU usage increases, and eventually the process may run out of memory or be terminated by the operating system.

Restarting the service might temporarily resolve the problem, but it does not fix the underlying cause.

Memory leaks in .NET applications are sometimes difficult to identify because .NET has a garbage collector that automatically manages managed memory. Developers often assume that objects will be removed automatically when they are no longer needed.

However, the garbage collector can only reclaim objects that are no longer reachable through active references. If an application accidentally keeps references to objects it no longer needs, those objects remain in memory.

Long-running services are particularly vulnerable because small retention problems can accumulate over time.

This article explains how memory leaks happen in .NET, how to identify them using diagnostic tools, how to inspect memory dumps, and how to fix common problems involving static collections, event handlers, timers, caches, background workers, and unmanaged resources.

Understanding Memory Management in .NET

.NET uses a garbage collector (GC) to manage managed memory.

When an application creates an object, the runtime allocates memory for it on the managed heap.

For example:

C#
public class Customer
{
    public int Id { get; set; }

    public string Name { get; set; } = string.Empty;
}

Creating an instance allocates memory:

Code
var customer = new Customer
{
    Id = 101,
    Name = "Rahul"
};

When the application no longer needs the object and there are no remaining references that keep it reachable, the garbage collector can reclaim its memory during a collection.

The important phrase is "no remaining references."

Consider this example:

C#
public void ProcessCustomer()
{
    var customer = new Customer
    {
        Id = 101,
        Name = "Rahul"
    };

    Console.WriteLine(customer.Name);
}

After the method completes, the local reference is no longer needed. Assuming nothing else references the object, it becomes eligible for garbage collection.

Now consider a different example:

Java
public static class CustomerCache
{
    public static List<Customer> Customers = new();
}

Another method adds customers to the collection:

C#
public void AddCustomer(int id, string name)
{
    CustomerCache.Customers.Add(new Customer
    {
        Id = id,
        Name = name
    });
}

Even after the method completes, the customer objects remain reachable through the static collection.

The garbage collector cannot reclaim them while they remain referenced.

If the application keeps adding customers without removing old entries, memory consumption continues to grow.

This is a typical managed memory leak.

Understanding the Difference Between High Memory Usage and a Memory Leak

Not every increase in memory consumption indicates a memory leak.

.NET applications allocate memory continuously while handling requests, processing messages, creating objects, and executing business logic.

The garbage collector periodically reclaims memory that is no longer needed.

The runtime may also retain committed heap memory for future allocations rather than immediately returning it to the operating system.

As a result, the process working set does not necessarily decrease after garbage collection.

Before investigating a memory leak, understand the different memory measurements.

Memory measurement

What it represents

Managed heap size

Memory occupied by managed objects

Working set

Physical memory currently resident for the process

Private memory

Private memory committed or allocated by the process

Allocation rate

Amount of managed memory allocated over time

Large Object Heap

Memory used by sufficiently large managed allocations

Pinned Object Heap

Memory associated with pinned managed objects

These measurements help distinguish different problems.

For example:

  • A high allocation rate does not automatically mean objects are leaking.

  • A large working set does not necessarily indicate a large managed heap.

  • A stable managed heap with increasing private memory may point toward unmanaged allocations or other native memory usage.

  • A managed heap that continues growing after full garbage collections deserves further investigation.

A useful starting point is to observe memory over time rather than looking at a single snapshot.

Why Long-Running .NET Services Develop Memory Leaks

Long-running applications often contain components that remain active for the lifetime of the process.

Examples include:

  • Background services.

  • Singleton services.

  • Static collections.

  • In-memory caches.

  • Event publishers and subscribers.

  • Timers.

  • Message consumers.

  • Connection managers.

  • Shared application state.

These components can accidentally retain objects long after their original work has completed.

Consider a background worker that processes messages continuously.

Each message creates several objects. Most of them should become eligible for garbage collection after processing.

However, if the worker stores references in an unbounded collection, those objects accumulate.

The problem may not appear during the first few minutes of execution. It becomes visible only after the service processes thousands or millions of messages.

This is why memory leak investigation should reproduce the application's real workload and observe memory over an extended period.

Common Causes of Memory Leaks in .NET Applications

Understanding common retention patterns helps narrow down the investigation.

Static collections that grow indefinitely

Static collections remain reachable for the lifetime of the application.

Consider this implementation:

C#
public static class RequestHistory
{
    public static List<string> Requests = new();
}

A middleware component records every incoming request:

Code
public async Task InvokeAsync(HttpContext context)
{
    RequestHistory.Requests.Add(
        context.Request.Path);

    await _next(context);
}

This implementation stores every request path in memory.

If the application handles thousands of requests per hour, the collection continues growing.

The garbage collector cannot remove the strings because they are still referenced by the static list.

A better solution is to use structured logging or a storage system designed for request history.

If the application genuinely needs an in-memory history, it should have an explicit retention policy.

For example:

C#
public class RequestHistory
{
    private readonly Queue<string> _requests = new();

    private readonly int _maximumEntries = 1000;

    private readonly object _lock = new();

    public void Add(string requestPath)
    {
        lock (_lock)
        {
            _requests.Enqueue(requestPath);

            while (_requests.Count > _maximumEntries)
            {
                _requests.Dequeue();
            }
        }
    }
}

This example limits the number of retained entries.

For concurrent production applications, choose a thread-safe collection or synchronization strategy appropriate to the workload. Also consider whether the application needs to retain request history at all.

The important principle is that in-memory collections should have a clear ownership and retention policy.

Event handlers that are never unsubscribed

Events are another common source of memory leaks.

Consider a long-lived publisher:

C#
public class NotificationPublisher
{
    public event EventHandler? NotificationReceived;

    public void Publish()
    {
        NotificationReceived?.Invoke(
            this,
            EventArgs.Empty);
    }
}

A subscriber registers an event handler:

C#
public class NotificationSubscriber
{
    public NotificationSubscriber(
        NotificationPublisher publisher)
    {
        publisher.NotificationReceived +=
            OnNotificationReceived;
    }

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

The publisher maintains a reference to the subscribed delegate.

The delegate references the subscriber instance.

As a result, the subscriber can remain reachable even when the rest of the application no longer needs it.

This becomes a problem when subscribers are created repeatedly but never unsubscribe.

One solution is to implement IDisposable:

C#
public class NotificationSubscriber : IDisposable
{
    private readonly NotificationPublisher _publisher;

    public NotificationSubscriber(
        NotificationPublisher publisher)
    {
        _publisher = publisher;

        _publisher.NotificationReceived +=
            OnNotificationReceived;
    }

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

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

The subscriber now removes its event handler when it is no longer needed.

In larger applications, event subscription lifetime should be part of the component's ownership design.

Unbounded caches

Caching improves performance by avoiding repeated database queries or expensive calculations.

However, a cache without an expiration or size policy can become a memory leak.

For example:

C#
public class ProductCache
{
    private readonly Dictionary<int, Product> _products = new();

    public void Add(Product product)
    {
        _products[product.Id] = product;
    }
}

If the application continuously adds new products and never removes old entries, the dictionary grows indefinitely.

A better approach is to use a cache with explicit expiration and size controls.

ASP.NET Core provides IMemoryCache:

C#
public class ProductCache
{
    private readonly IMemoryCache _cache;

    public ProductCache(IMemoryCache cache)
    {
        _cache = cache;
    }

    public void Add(Product product)
    {
        _cache.Set(
            $"product:{product.Id}",
            product,
            new MemoryCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow =
                    TimeSpan.FromMinutes(30),

                Size = 1
            });
    }
}

Register the cache with an appropriate size limit:

Code
builder.Services.AddMemoryCache(options =>
{
    options.SizeLimit = 10000;
});

When a size limit is configured, entries must specify their size.

The size unit is application-defined. In this example, every product counts as one unit.

A cache size limit does not automatically measure the actual memory footprint of each object. Choose an appropriate sizing strategy and combine it with expiration policies.

For applications with large or variable-sized objects, account for their relative memory cost.

Timers and callbacks that retain objects

Timers are useful in background processing, scheduled tasks, and periodic monitoring.

However, a timer can keep references to its callback target.

Consider this example:

C#
public class DataMonitor
{
    private readonly Timer _timer;

    public DataMonitor()
    {
        _timer = new Timer(
            CheckData,
            null,
            TimeSpan.Zero,
            TimeSpan.FromMinutes(1));
    }

    private void CheckData(object? state)
    {
        Console.WriteLine("Checking data...");
    }
}

If a DataMonitor instance is no longer required but its timer is still running, the timer may keep the object reachable through its callback.

Implement disposal:

C#
public class DataMonitor : IDisposable
{
    private readonly Timer _timer;

    public DataMonitor()
    {
        _timer = new Timer(
            CheckData,
            null,
            TimeSpan.Zero,
            TimeSpan.FromMinutes(1));
    }

    private void CheckData(object? state)
    {
        Console.WriteLine("Checking data...");
    }

    public void Dispose()
    {
        _timer.Dispose();
    }
}

Disposing the timer releases its resources and stops future callbacks.

For asynchronous background work, use a lifecycle-aware implementation rather than allowing timers and callbacks to outlive their intended owner.

Incorrect dependency injection lifetimes

Dependency injection can also contribute to memory retention problems.

Consider an application that registers a service as a singleton:

Code
builder.Services.AddSingleton<OrderService>();

A singleton remains available for the lifetime of the application.

If that singleton retains references to large collections, request-specific objects, or other services with shorter intended lifetimes, those objects may remain alive much longer than expected.

For example, a singleton should not directly capture a scoped DbContext.

Instead, use IServiceScopeFactory when a singleton background service needs to perform scoped database operations:

C#
public class OrderWorker : BackgroundService
{
    private readonly IServiceScopeFactory _scopeFactory;

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

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

            var dbContext = scope.ServiceProvider
                .GetRequiredService<AppDbContext>();

            var orders = await dbContext.Orders
                .Where(x => x.Status == "Pending")
                .ToListAsync(stoppingToken);

            // Process orders here.

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

The scope is disposed after each iteration.

This allows scoped services and their associated resources to be released instead of retaining them for the entire lifetime of the background worker.

The worker should also avoid retaining unnecessary entity collections between iterations.

Large objects retained longer than necessary

.NET uses a Large Object Heap (LOH) for sufficiently large managed allocations.

Objects around 85,000 bytes or larger are generally allocated on the LOH.

Large byte arrays and strings are common examples.

Consider a file-processing service:

C#
public async Task ProcessFileAsync(
    Stream inputStream,
    CancellationToken cancellationToken)
{
    using var memoryStream = new MemoryStream();

    await inputStream.CopyToAsync(
        memoryStream,
        cancellationToken);

    var fileBytes = memoryStream.ToArray();

    await ProcessBytesAsync(
        fileBytes,
        cancellationToken);
}

This implementation creates large allocations for the memory stream and the copied byte array.

If many files are processed concurrently, memory usage can increase significantly.

The problem might be excessive allocation rather than a traditional memory leak.

A better approach is to process the stream incrementally:

Code
public async Task ProcessFileAsync(
    Stream inputStream,
    Stream outputStream,
    CancellationToken cancellationToken)
{
    await inputStream.CopyToAsync(
        outputStream,
        81920,
        cancellationToken);
}

For actual file processing, the application can read and process fixed-size chunks instead of loading the complete file into memory.

This reduces large temporary allocations and helps keep memory consumption predictable.

Unmanaged resources that are not disposed

Not all resources are managed by the .NET garbage collector.

Examples include:

  • File handles.

  • Database connections.

  • Native memory allocations.

  • Operating system handles.

  • Some graphics and networking resources.

These resources require proper cleanup.

For example:

C#
public void ReadFile(string filePath)
{
    var stream = new FileStream(
        filePath,
        FileMode.Open);

    // Read file.
}

The stream is never disposed.

Although finalization may eventually release certain resources, relying on the finalizer is not a good resource-management strategy.

Use using or await using:

C#
public async Task ReadFileAsync(
    string filePath,
    CancellationToken cancellationToken)
{
    await using var stream = new FileStream(
        filePath,
        FileMode.Open,
        FileAccess.Read,
        FileShare.Read,
        bufferSize: 81920,
        useAsync: true);

    // Process the file.
}

This ensures the stream is disposed when the method completes, including when an exception occurs.

For custom types that own unmanaged resources, implement the appropriate disposal pattern and release those resources deterministically.

Starting the Investigation With dotnet-counters

Before collecting memory dumps, determine whether the application is actually experiencing memory growth.

.NET provides dotnet-counters, a command-line diagnostic tool that monitors runtime performance counters.

Install it using:

Code
dotnet tool install --global dotnet-counters

Find the running .NET processes:

Code
dotnet-counters ps

The command displays available .NET processes and their process identifiers.

Start monitoring the application:

Code
dotnet-counters monitor --process-id 12345 System.Runtime

Replace 12345 with the actual process ID.

The tool displays runtime metrics that help identify memory and garbage collection behavior.

Important counters include:

Counter

What it helps identify

Working Set

Physical memory used by the process

GC Heap Size

Size of the managed heap

Allocation Rate

How quickly the application allocates memory

Gen 0 GC Count

Frequency of short-lived garbage collections

Gen 1 GC Count

Frequency of intermediate collections

Gen 2 GC Count

Frequency of full-generation collections

LOH Size

Memory occupied by large managed objects

GC Fragmentation

Fragmentation within the managed heap

Time in GC

Time spent performing garbage collection

The exact counter names and display format can vary between runtime versions.

What should you look for?

Suppose you observe the following pattern:

Observation

Possible explanation

Working set increases, GC heap remains stable

Native memory, other process memory, or retained committed memory

GC heap increases continuously

Managed objects may be accumulating

Allocation rate is high, but heap stabilizes

High temporary allocation rather than necessarily a leak

Gen 2 collections increase frequently

Significant long-lived object or heap pressure

LOH size keeps increasing

Large objects may be retained or allocated excessively

Memory increases after each scheduled job

Job processing may retain objects or resources

These patterns are clues, not proof.

For example, a high Gen 2 collection count does not automatically mean a memory leak. It may indicate that the application is creating large amounts of temporary data.

The goal is to identify whether memory remains elevated after garbage collection and whether the retained object population continues growing.

Reproducing the Memory Growth Pattern

One of the most useful steps in memory leak investigation is to reproduce the application's normal workload.

Consider a background service that processes customer records.

If memory increases after every processing cycle, the investigation should focus on what the worker retains between cycles.

A useful test sequence is:

  1. Start the application with a clean process.

  2. Record the initial memory measurements.

  3. Execute a representative workload.

  4. Allow garbage collection to occur naturally.

  5. Record memory again.

  6. Repeat the same workload several times.

  7. Compare the managed heap and object counts.

For example, if a worker processes 10,000 messages per cycle, execute the same workload repeatedly.

If the managed heap continues growing after repeated cycles, inspect which object types are accumulating.

Avoid forcing garbage collection after every operation in production code. Explicit calls to GC.Collect() usually do not solve the underlying retention problem and can negatively affect performance.

For controlled diagnostics, a memory snapshot taken after a collection can help reveal which objects remain alive.

Collecting a Memory Dump With dotnet-dump

When counters indicate sustained memory growth, collect a memory dump.

A memory dump captures the state of a process at a particular moment.

It can contain information about:

  • Managed objects.

  • Object references.

  • Garbage collection roots.

  • Threads and stacks.

  • Runtime state.

  • Native memory information, depending on dump type and platform.

Install the diagnostic tool:

Code
dotnet tool install --global dotnet-dump

Find the application process ID:

Code
dotnet-counters ps

Collect a dump:

Code
dotnet-dump collect --process-id 12345

The command generates a dump file that can be analyzed separately.

For a long-running service, consider collecting two dumps at different times while the application experiences similar workloads.

For example:

  • First dump after the application has warmed up.

  • Second dump after several hours of normal processing.

Comparing the dumps can help identify which object types are increasing.

Dump collection can consume significant disk space and additional system resources. In memory-constrained containers, collection itself can increase memory pressure enough to trigger termination.

Plan dump collection carefully in production and protect dump files because they may contain sensitive application data.

Analyzing the Memory Dump

After collecting a dump, open it using the diagnostic analyzer:

Code
dotnet-dump analyze <dump-file>

The command opens an interactive diagnostic session.

You can use SOS commands to inspect the managed heap and object references.

Identify the largest object types

Start with:

Code
dumpheap -stat

This command displays a summary of objects grouped by type.

The output includes:

  • Method table.

  • Number of objects.

  • Total size.

  • Class name.

For example:

Code
Statistics:

MT              Count       TotalSize    Class Name
00007f...       200000      4800000      Customer
00007f...       206770      19494060     System.String
00007f...       1749        95696        System.SByte[]
00007f...       467         416464       System.Byte[]

In this example, the application contains a large number of customer objects and strings.

That does not automatically mean either type is leaking.

The next step is to determine why these objects remain in memory.

Inspect individual objects

Use dumpheap with the method table of the type you want to inspect.

For example:

Code
dumpheap -mt <method-table>

This displays instances of the selected type.

Choose an object address from the output and inspect it:

Code
dumpobj <object-address>

This helps identify the object's fields and current state.

Find why an object remains in memory

The gcroot command is one of the most useful tools for finding managed memory leaks.

Run:

Code
gcroot <object-address>

The command identifies reference paths from garbage collection roots to the selected object.

A garbage collection root is a reference that keeps an object reachable.

Examples include:

  • Static fields.

  • Active stack references.

  • GC handles.

  • Runtime-related roots.

  • References held by other reachable objects.

Consider a simplified reference chain:

Code
Static CustomerCache
        |
        v
List<Customer>
        |
        v
Customer[]
        |
        v
Customer Object

This indicates that the customer remains alive because it is referenced by a static cache.

The application code responsible for maintaining that collection is a good place to investigate.

This is much more useful than simply observing that the customer objects occupy memory.

Comparing Memory Dumps Over Time

A single dump shows the state of the application at one moment.

Two or more dumps help identify which objects are accumulating.

Consider the following example:

Object type

First dump

Second dump

Customer

10,000

50,000

Order

5,000

5,200

String

25,000

110,000

Byte array

500

550

The customer and string counts have increased significantly.

This suggests that the application might be retaining customer-related data.

The next step is to inspect representative objects and identify their reference paths.

A growing object count alone is not proof of a leak. The application might legitimately retain more data as its workload changes.

Compare snapshots after equivalent workload periods and investigate whether the retained data should still exist.

For large applications, Visual Studio memory analysis, PerfView, and other profiling tools can help compare object populations and allocation behavior.

Investigating Memory Growth in a BackgroundService

Long-running background services deserve special attention because they execute repeatedly without the application process being restarted.

Consider a worker that processes queued customer messages.

A simplified implementation might look like this:

C#
public class CustomerWorker : BackgroundService
{
    private readonly ILogger<CustomerWorker> _logger;

    private readonly List<Customer> _processedCustomers = new();

    public CustomerWorker(
        ILogger<CustomerWorker> logger)
    {
        _logger = logger;
    }

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

            if (customer != null)
            {
                _processedCustomers.Add(customer);

                _logger.LogInformation(
                    "Processed customer {CustomerId}",
                    customer.Id);
            }
        }
    }

    private Task<Customer?> GetNextCustomerAsync(
        CancellationToken cancellationToken)
    {
        // Retrieve the next customer.
        throw new NotImplementedException();
    }
}

The problem is the _processedCustomers collection.

Every processed customer remains referenced by the worker.

Because the worker is a singleton-like hosted component that lives for the application's lifetime, the collection can continue growing indefinitely.

If the worker processes one million messages, it could retain a million customer objects.

The correct solution depends on why the collection exists.

If the application only needs to log completed processing, use structured logging.

If it needs to track processing statistics, store aggregate counters rather than every customer object.

For example:

C#
public class CustomerWorker : BackgroundService
{
    private readonly ILogger<CustomerWorker> _logger;

    private long _processedCount;

    public CustomerWorker(
        ILogger<CustomerWorker> logger)
    {
        _logger = logger;
    }

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

            if (customer == null)
            {
                await Task.Delay(
                    TimeSpan.FromSeconds(1),
                    stoppingToken);

                continue;
            }

            await ProcessCustomerAsync(
                customer,
                stoppingToken);

            Interlocked.Increment(ref _processedCount);
        }
    }

    private Task<Customer?> GetNextCustomerAsync(
        CancellationToken cancellationToken)
    {
        // Retrieve the next customer.
        throw new NotImplementedException();
    }

    private Task ProcessCustomerAsync(
        Customer customer,
        CancellationToken cancellationToken)
    {
        // Process the customer.
        return Task.CompletedTask;
    }
}

This implementation tracks the number of processed customers without retaining every customer object.

The example also illustrates why background workers should have a clear policy for their in-memory state.

Understanding Object Pools and ArrayPool

Some applications process large amounts of data and frequently allocate byte arrays.

Repeated allocations can increase garbage collection pressure.

.NET provides ArrayPool<T> to reuse arrays rather than allocating new ones for every operation.

For example:

C#
public async Task ProcessStreamAsync(
    Stream input,
    Stream output,
    CancellationToken cancellationToken)
{
    var buffer = ArrayPool<byte>.Shared.Rent(81920);

    try
    {
        int bytesRead;

        while ((bytesRead = await input.ReadAsync(
            buffer.AsMemory(),
            cancellationToken)) > 0)
        {
            await output.WriteAsync(
                buffer.AsMemory(0, bytesRead),
                cancellationToken);
        }
    }
    finally
    {
        ArrayPool<byte>.Shared.Return(buffer);
    }
}

The array is returned to the pool even if an exception occurs.

However, returning an array to the pool does not mean the memory is immediately released to the operating system. The pool may retain arrays for future reuse.

This is expected behavior.

For sensitive data, consider clearing the buffer when returning it:

Code
ArrayPool<byte>.Shared.Return(
    buffer,
    clearArray: true);

The clearing operation has a performance cost, so use it when the data's sensitivity requires it.

Object pooling should also be applied carefully. An unbounded or incorrectly implemented pool can retain more memory than necessary.

Pooling reduces repeated allocation costs; it is not a substitute for a memory-retention policy.

Understanding Large Object Heap and Fragmentation

The Large Object Heap stores sufficiently large managed allocations.

Common examples include:

  • Large byte arrays.

  • Large character arrays.

  • Large strings.

  • Large object graphs.

Repeated allocation and release of large objects can create memory pressure and fragmentation.

For example:

C#
public byte[] ReadDocument(Stream stream)
{
    using var memoryStream = new MemoryStream();

    stream.CopyTo(memoryStream);

    return memoryStream.ToArray();
}

If this method processes hundreds of large documents concurrently, it can create substantial allocation pressure.

A better design is to stream the document to its destination or process it in chunks.

For memory-intensive applications, monitor the LOH and pinned object heap as well as the overall managed heap.

Also investigate whether large arrays are being pinned for long periods.

Pinning prevents the garbage collector from moving an object. Excessive pinning can interfere with heap compaction and increase fragmentation.

Use pinned memory only when necessary, and keep its lifetime as short as possible.

Investigating Unmanaged Memory Growth

Sometimes the managed heap remains relatively stable while the application's working set or private memory continues increasing.

In that situation, the problem may not be a traditional managed object leak.

Possible causes include:

  • Native library allocations.

  • Unmanaged buffers.

  • Native handles.

  • Interoperability code.

  • Memory-mapped files.

  • Incorrect disposal of native resources.

  • Runtime or third-party native components.

For example, an application might allocate unmanaged memory:

Code
IntPtr memory = Marshal.AllocHGlobal(1024);

If the application never releases the allocation, the memory remains allocated outside the normal managed heap.

Release it explicitly:

Code
IntPtr memory = Marshal.AllocHGlobal(1024);

try
{
    // Use unmanaged memory.
}
finally
{
    Marshal.FreeHGlobal(memory);
}

For custom types that own unmanaged memory, implement a correct disposal pattern.

If native memory is involved, use appropriate platform profiling tools and inspect native allocations. Managed heap analysis alone may not reveal the full cause.

Building a Practical Memory Leak Investigation Workflow

When a production service experiences increasing memory consumption, avoid making random code changes.

Follow a structured diagnostic process.

Step 1: Confirm the memory growth

Start by monitoring:

  • Working set.

  • Managed heap size.

  • Allocation rate.

  • Generation 2 collections.

  • LOH size.

  • Private memory.

Observe the application under a representative workload.

Determine whether memory grows continuously or stabilizes after garbage collection.

Step 2: Identify when memory increases

Correlate memory usage with application activity.

For example:

  • Does memory increase after every scheduled job?

  • Does it increase after processing a particular message type?

  • Does it increase when users upload files?

  • Does it increase after cache population?

  • Does it increase when external API calls fail?

  • Does it increase after a specific endpoint receives traffic?

This helps narrow the investigation to a specific workload or component.

Step 3: Capture memory dumps

Capture at least two snapshots under comparable conditions.

Avoid collecting dumps unnecessarily because they can be large and contain sensitive information.

Step 4: Identify growing object types

Use dumpheap -stat to find object types that consume the most memory.

Compare object counts and total sizes across snapshots.

Step 5: Find reference paths

Use dumpobj and gcroot to understand why representative objects remain reachable.

Trace the references back to application-owned components.

Step 6: Fix the ownership or retention problem

Typical fixes include:

  • Removing obsolete references.

  • Bounding in-memory collections.

  • Adding cache expiration.

  • Unsubscribing from events.

  • Disposing timers and streams.

  • Correcting dependency injection lifetimes.

  • Releasing unmanaged memory.

  • Reducing unnecessary large allocations.

Step 7: Validate the fix

Run the same workload again.

Compare the memory profile before and after the change.

A successful fix should prevent the unwanted object population from growing indefinitely.

Monitoring Memory Usage in Production

Memory leak investigations should not begin only after an application crashes.

Long-running services should have memory monitoring built into their operational practices.

Useful measurements include:

Metric

Purpose

Process working set

Tracks physical memory usage

Private memory

Helps identify overall private memory growth

Managed heap size

Tracks managed memory

Allocation rate

Identifies excessive allocation

Gen 2 collection frequency

Helps identify long-lived heap pressure

LOH size

Tracks large object allocations and retention

GC fragmentation

Helps identify heap layout problems

Active requests

Correlates memory with request load

Queue length

Helps identify message-processing backlogs

Cache size

Helps identify unbounded caching

Container memory usage

Tracks memory against deployment limits

For containerized applications, monitor both process-level metrics and the container's memory limit.

A process may be terminated by the container environment before it reaches a managed OutOfMemoryException.

For distributed services, consider collecting runtime metrics centrally and using diagnostic tools such as dotnet-monitor when remote collection of traces or dumps is required.

Memory dumps should be handled as sensitive production artifacts. Restrict access, encrypt storage where appropriate, and define a retention policy.

Common Mistakes During Memory Leak Investigation

Calling GC.Collect() to solve memory growth

Forcing garbage collection does not remove objects that are still reachable.

If a static collection holds thousands of customer objects, calling GC.Collect() will not make those objects eligible for collection.

Find and remove the unwanted references instead.

Restarting the service without investigating

Restarting may temporarily release memory, but it hides the underlying problem.

Capture diagnostic information before restarting whenever practical.

Looking only at working set

Working set includes memory beyond the managed heap.

A high working set does not automatically indicate a managed memory leak.

Compare multiple memory measurements before deciding where to investigate.

Assuming every large allocation is a leak

A large temporary allocation may be released after an operation completes.

The problem may be allocation pressure rather than retained objects.

Use heap snapshots and reference analysis to distinguish the two.

Keeping unlimited data in singleton services

Singleton services live for the lifetime of the application.

Avoid storing every request, message, or processed entity in singleton-owned collections unless the collection has a deliberate retention policy.

Forgetting to dispose resources

Streams, timers, connections, and other disposable resources should have clear ownership and cleanup behavior.

Use using, await using, or an appropriate disposal pattern.

Collecting only one memory dump

One snapshot may show that an object occupies memory, but it does not reveal whether the object population is growing.

Compare snapshots collected after equivalent workloads.

Conclusion

Memory leaks in long-running .NET services can gradually reduce application performance, increase garbage collection activity, and eventually cause an application to run out of memory.

The garbage collector handles managed memory automatically, but it cannot reclaim objects that remain reachable through active references. Static collections, unbounded caches, event subscriptions, timers, background workers, and incorrect dependency lifetimes are common sources of unwanted object retention.

The most effective way to investigate these problems is to follow a structured process.

Start by monitoring memory with dotnet-counters. Confirm whether managed heap usage is growing, then collect memory dumps using dotnet-dump. Inspect object populations with dumpheap -stat and use gcroot to identify why objects remain reachable.

Once the reference chain is understood, fix the underlying ownership or retention problem and repeat the same workload to verify the result.

For production services, memory monitoring, bounded caches, deterministic resource disposal, and well-defined background worker lifetimes should be part of normal application design.

The goal is not to force the garbage collector to run more frequently. It is to ensure that objects and resources are released when the application no longer needs them.