Showing posts from February, 2013

Hidden memory leaks in WinForm Apps

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 th…