Search code examples
c#memorymemory-leaksshowdialog

ShowDialog() memory leak workaround


In my company's enterprise solution, I am going through and cleaning out as many memory leaks as I can.

We have a BaseCaptureForm which is inherited by many other forms (for example, RecommendationCaptureForm). Throughout the system (for example) this RecommendationCaptureForm is called modally (ShowDialog()). Now as far as I know, when forms are opened modally they should be wrapped in a using statement or disposed of when done.

There is a dispose method in the BaseCaptureForm which is never hit. I put in a finalizer and it is never hit as well. ANTS Memory Profiler shows that all these forms are retained in memory.

Does anyone have any suggestions on how I can go about disposing these capture forms (which aren't open for all that long) in order to stop leaking memory? There are millions of ShowDialog calls throughout the system and I was wondering if anyone else has hit this problem?

Edit To clarify, is there something I can do in the BaseCaptureForm to automatically dispose itself once closed? I cannot go through all the ShowDialog() calls in hoping of disposing them. Calling the dispose method in the OnClosed event of the form causes a nasty flicker.


Solution

  • Unfortunately, there is no easy way to do this. What you have is bad code, and that bad code has to be corrected just like all other bad code: by fixing it and replacing it with good code. There are no band-aids to apply here; the band-aid is the finalizer of the Form calling Dispose(), which is never guaranteed to happen. If the object is ineligible for collection, then ANTS Memory Profiler will show you what's holding onto a reference to it.