I did nice winforms 2.0 application and it’s working great and customers are still happy but unfortunatelly I cannot solve one issue. The problem is that after using app for a couple of hours, gdi user handles number is rising and rising and finally process cannot allocate more objects and app crashes…
I’m not doing anything fancy, it’s regular app, a few forms, a few more modal forms, a few datagridviews and a lot tablelayoutpanels where I’m adding a lot labels and textboxes.
My questions are:
- are there any “recommended-practises”
concerning adding/removing regular system
controls on forms at runtime (dgv/tlp) - how to detect system handles’
leaks – preferably using visual
studio and a kind of free plugin
(profiler?)
Detecting graphics and window handle leaks is very difficult. As to a particular strategy for finding them at runtime, I can’t suggest anything (though I’d love to hear someone else’s!).
As for preventing them, here are a couple of reminders:
Controlclass’s finalizer will callDispose(), this is non-deterministic. You are not guaranteed that ANY object will EVER get finalized by the garbage collector. It’s likely that it will, but it’s not a guarantee.Formis shown in a NON-MODAL way (meaning throughShow(), NOTShowDialog()), then when theFormcloses it will deterministically callDispose(). Forms that are shown throughShowDialog()must haveDispose()called manually in order to deterministically clean up the control handle.Dispose()on any object that you explicitly create that implementsIDisposable. This INCLUDESForms,Controls,Graphicsobjects, even the graphics helper classes likePenandBrush. All of those classes implementIDisposable, and all of them need to be disposed of as soon as you no longer need them.Penand aBrushare fairly lightweight to create, they do take up handles and need to be disposed of when you’re finished. Rather than creating them all the time, create a cache manager that allows you to pass in the parameters that you would use in the constructor for those objects and keep that object around. Repeated calls with the same parameters should still only use one single instance. You can then flush your cache on a periodic basis or at specific places in your application if you know where those would be.Following those guidelines will greatly reduce–if not eliminate–your handle leaks.