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:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
}Creating an instance allocates memory:
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:
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:
public static class CustomerCache
{
public static List<Customer> Customers = new();
}Another method adds customers to the collection:
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:
public static class RequestHistory
{
public static List<string> Requests = new();
}A middleware component records every incoming request:
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:
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:
public class NotificationPublisher
{
public event EventHandler? NotificationReceived;
public void Publish()
{
NotificationReceived?.Invoke(
this,
EventArgs.Empty);
}
}A subscriber registers an event handler:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
dotnet tool install --global dotnet-countersFind the running .NET processes:
dotnet-counters psThe command displays available .NET processes and their process identifiers.
Start monitoring the application:
dotnet-counters monitor --process-id 12345 System.RuntimeReplace 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 |
Join the conversation! Your thoughts help the community grow.