0. Why This Article Exists
It's currently 1:07 AM on Saturday, October 14, 2023. After seven consecutive days of work, I finally have a day off. I just got back from a night out, and it's well past my usual nap time. My head is clear as a watermelon 🤯, feeling like I've been refreshed. I know staying up late isn't good, but since I can't sleep right now, I'll just post a casual blog entry.
Lately, I've been involved in building a project with high requirements for runtime stability, and a key factor affecting runtime stability is memory leaks. Even experienced .NET experts find it difficult to avoid them. I often mess up too, only realizing the issues when reviewing my own code.
It's truly a pity if a developer causes a production incident due to minor coding practices, potentially facing job loss or being "sacrificed" for the mistake.
![]() |
|---|
| Figure 1 |
So today, I'll list up the memory leak scenarios and code examples I can currently recall or find online, as a reminder to myself. Even after mastering the scenarios I'm about to introduce, you might still make the same mistakes, because I do it all the time. But knowing is better than not knowing.
1. What is a memory leak?
A memory leak in .NET generally refers to objects that are no longer needed by the application still being referenced by other objects, thereby preventing the Garbage Collector (GC) from reclaiming their memory. This can lead to performance degradation and out-of-memory exceptions.
If you are not yet familiar with what GC is, you can check out this comic I translated: Explaining .NET Garbage Collection (GC) Principles in a Comic: https://cat.aiursoft.cn/post/2023/7/18/cartoon-dotnet-garbage-collection
The memory occupied by application objects is generally the memory space allocated by the application on the heap, known as "managed memory." In the .NET world, there is also "unmanaged memory." When performing memory analysis, I frequently observe high unmanaged memory usage, but it is rarely noticed by developers. We often use classes that implement the IDisposable interface and the Dispose() method, commonly those related to networking, files, and so on. If you use these classes and forget to Dispose them, it will result in unmanaged memory leaks.
Let's begin the introduction.
2. Memory Leaks Caused by Anonymous Methods Capturing Class Members
Anonymous methods that capture class members create a strong reference, preventing the class instance from being collected by the garbage collector. Here is an example:
public class MyClass
{
private int _id;
public MyClass(int id)
{
_id = id;
}
public void DoSomething(JobQueue jobQueue)
{
// 这里的匿名函数捕获了_id成员
jobQueue.AddJob(() => Logger.Log("Job {0} done", _id));
}
}
public class JobQueue
{
private List<Action> _jobs = new List<Action>();
public void AddJob(Action job)
{
_jobs.Add(job);
}
public void ExecuteJobs()
{
foreach (var job in _jobs)
{
job();
}
_jobs.Clear();
}
}
In this code, when the DoSomething method is called on an instance of the MyClass class, an anonymous function is added as a task to an instance of the JobQueue class. This anonymous function captures the _id member, so as long as the JobQueue instance exists and references this task delegate, it also holds a reference to the MyClass instance. This leads to a memory leak, because even if the MyClass instance is no longer referenced by other objects, it will not be collected by the garbage collector.
To avoid this memory leak, you can use a local variable instead of the _id member, for example:
public void DoSomething(JobQueue jobQueue)
{
// 使用一个局部变量来替代_id成员
int id = _id;
jobQueue.AddJob(() => Logger.Log("Job {0} done", id));
}
This prevents the creation of a strong reference and instead creates a weak reference. When instances of the MyClass class are no longer referenced by other objects, they can be collected by the garbage collector. If you want to learn more about memory leaks caused by anonymous functions capturing class members and their solutions, you can refer to this article.
3. Memory Leaks Caused by the Event Lifecycle
Events are also a common culprit behind memory leaks, but the introduction of anonymous methods has reduced their frequency of use. That said, it is still worth discussing. If a class subscribes to an event of a class with a longer lifecycle, it creates a strong reference, which keeps the subscriber alive even after it is no longer needed.
public class Publisher
{
public event EventHandler SomeEvent;
public void RaiseEvent()
{
SomeEvent?.Invoke(this, EventArgs.Empty);
}
}
public class Subscriber
{
public Subscriber(Publisher publisher)
{
publisher.SomeEvent += OnSomeEvent;
}
private void OnSomeEvent(object sender, EventArgs e)
{
// Do something
}
}
In this code, each created Subscriber instance subscribes to the SomeEvent event raised by the Publisher instance passed to its constructor. If the Publisher instance has a longer lifetime than the Subscriber instance—for example, if it is a static or singleton object—the Subscriber instance will not be garbage collected unless it explicitly unsubscribes from the event. To avoid this memory leak, the Subscriber class should unsubscribe from the event when it is no longer needed, or use "weak event handlers" that do not create strong references to the subscriber. The sample code is as follows:
public class Subscriber
{
private WeakReference weakPublisher;
public Subscriber(Publisher publisher)
{
weakPublisher = new WeakReference(publisher);
publisher.SomeEvent += OnSomeEvent;
}
private void OnSomeEvent(object sender, EventArgs e)
{
// Do something
var publisher = weakPublisher.Target as Publisher;
if (publisher == null)
{
// Publisher 已被垃圾收集,因此取消订阅该事件
((Publisher)sender).SomeEvent -= OnSomeEvent; // 这是你需要添加的代码
}
}
}
This thing is quite strange. It’s possible that experienced developers have used it before, but I only learned about WeakReference after researching it. I haven’t tried the code snippet above. Please try to write code that you understand and can manage. I don’t even remember using the C# event keyword in backend applications; maybe it’s used more on the client side?
4. Memory Leaks Caused by Static Variables
Sometimes, after learning about new features or clever techniques, we can't help but use them right away, even though we haven't fully understood them yet. This often leads to problems. Examples include static variables and static events.
A static variable is a variable that the GC does not collect; such variables are also known as GC Roots. Static variables are intended to be kept in memory for an extended period. This typically does not result in significant memory overhead. However, objects referenced by GC Roots are also not collected by the GC, which can cause issues.
But if you use a collection-type static variable, for example:
public class MyClass
{
static List<MyClass> _instances = new List<MyClass>();
public MyClass()
{
_instances.Add(this);
}
}
So every time new MyClass is called, the static variable _instances grows a little, and as long as the application keeps running, it is never released, gradually expanding.
Static events need no further explanation.
5. Memory Leaks Caused by In-Memory Caching
This situation is very similar to the previous one and is quite common. Many developers like to add a collection property such as List<T> or Dictionary<int, T> to objects (especially those with a singleton lifetime) to cache some data. If the collection type is hardcoded and read-only, there is no problem. However, if your collection type allows items to be added, things can get troublesome. It is rare for anyone to manually write code and algorithms to remove unused objects from it. With only additions and no removals, this collection property will keep growing larger and larger. If the lifetime is long enough, it will eventually exhaust memory.
I previously wrote an article about choosing collection types. If you are interested, please check it out: Who is your type? A guide to choosing between IEnumerable, IQueryable, and ICollection: https://cat.aisoft.cn/post/2023/3/10/a-guide-to-ienumerable-iqueryable-and-icollection
Here, read-only collection types do not refer to collection properties modified with the readonly keyword, but rather to properties defined by read-only interfaces such as IReadOnlyList<T> and IReadOnlyDictionary<int, T>.
It is recommended to use the more specialized IMemoryCache when you encounter scenarios requiring this kind of in-memory caching. The .NET MemoryCache will release memory under certain conditions, including:
- The expiration time of a cache item is reached, or the cache item is actively removed;
- The priority of a cache item is set to
CacheItemPriority.LoworCacheItemPriority.NeverRemove; when memory pressure is high, cache items may be reclaimed; - A cache item is associated with an
IChangeToken; when thatIChangeTokenchanges, the cache item is removed; - The cache object is disposed, or a new MemoryCache object is created.
If necessary, you can introduce external caching solutions such as Redis or MemCached, but only if it is truly necessary. If in-memory caching can solve the problem and introducing an external cache offers no significant benefit, you should carefully weigh the trade-offs.
6. Unmanaged Memory Leaks Caused by Not Calling Dispose
This is the easiest part to handle. Pay attention to classes related to operations involving networks, files, etc., as well as various stream-related classes. If they implement IDisposable or have a Dispose method, wrap the objects that need to be disposed in a using statement.
I have once encountered developers who relied solely on the GC to handle this situation. The GC can indeed handle it, because such classes generally have a finalizer, which looks like this:
~MyClassFinalizer()
{
// ......
}
It generally calls the Dispose() method.
However, finalizers come with a significant performance overhead. For details, please refer to my blog post: .NET Performance Tips: Why You Should Avoid Using Finalizers?
7. Incorrect Use of unsafe or Other Direct Memory Manipulation Methods
In .NET, you can allocate unmanaged memory using unsafe. Later, more "closer-to-memory" features like Span and Marshal were introduced. It's not that you can't use them, but you should be clear about what you're doing when you do. I suspect most people only learn how to use them when they actually need to, so I won't cover them here.
Summary
I was writing this late at night, and my mind was no longer very clear during the process. As a result, the text may be disorganized and contain errors or omissions. Please forgive me, and feel free to leave a comment pointing out any issues. I truly appreciate it. Wishing everyone success in getting rid of annoying memory leaks 🎉🎉

Comments (0)
No comments yet. Be the first to leave one!