Skip to main content

Posts

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 most of the time the GC does a great job 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 effectively disposing FrmFoo... There are two issues with the following line, The first one, the GC will never be able to collect the garbage created inside the anonymous function generated by the C# compiler to back 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 that function and cannot be destroyed; hence the memory leak.