Dealing with memory leaks in .NET apps it is always a hard thing to do. While the GC does a great job (most of the time) freeing us to worry about memory management, there are some edge cases where we have to be very careful to not screw things up.
In this post I am going to show a common issue I see when doing code reviews on WinForm apps.
First, let’s take a look at this code and see what it is wrong with it.
As you can guess, the problem with the code above is that creates a memory leak ;). But why? We are (correctly?) disposing FrmFoo...
This line of code creates two issues,
The first one, the GC will never be able to collect the garbage created inside the closure generated by the lambda expression attached to the control’s click event. Even when we are disposing the form, the object created by the C# compiler is rooted inside the scope of the closure and cannot be destroyed, hence the memory leak.
The second one, we don’t have access from an outer scope to the delegate attached to the click event, so we cannot effectively remove it while disposing the form. Which is a good practice and almost no one does it (including myself).
For the last issue, I made an extension method that solves the problem, but the first one still remains....
This is a nice way to implement the same use case without introducing memory leaks.
I know this is a trivial example and the impact of memory issues is almost none, but be careful with these kind of stuff, usually, issues like these are really tough and takes a lot of time to deal with them.
Here, the list of tools I frequently use to work on performance/memory related issues.