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 dispos开发者_运维问答ing 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.
Depending on how you use the forms after they have been closed (*), you can call Dispose() from within the FormClosed event handler.
I don't see the "nasty flicker" you refer to, one thing you might try is to set this.Visible = false
in the FormClosed event handler.
(*) You may be safe as long as you are not exposing any controls or properties of controls via publicly-visible properties or methods of your form. One way to avoid this is to implement such public properties with backing fields, and copy any data from controls into these backing fields before the form is closed.
Without seeing code it's difficult to see if this would be realistic in your scenario. And to be honest I'd be inclined to bite the bullet and clean up the calls by adding using
statements.
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.
if dispose of the dialog is never called this can be an indicator of an exception which is thrown inside your form. Take a look at this blogpost.
Have you implemented the "Ms Dispose Pattern"? Which can even help with your solution. Maybe you can provide some code?
Hope this can be a help for you...
精彩评论