Lifetime of objects in a collection in VB.Net -


i'm trying figure out lifetime of tmptabpages in following bit of code. lets assume form has empty tabcontrol named mytabcontrol, there's collection of strings called namecollection.

private sub form1_load(byval sender system.object, byval e system.eventargs) handles mybase.load     each itm in namecollection         dim tmptabpage new tabpage(itm.tostring)          'add controls tmptabpage          mytabcontrol.tabpages.add(tmptabpage)     next end sub 

since scope of tmptabpage for/next block, typically it's lifetime until end of block right? since added collection has scope outside of block same lifetime collection, or in case mytabcontrol? finally, if call mytabcontrol.tabpages.clear tmptabpages in collection destroyed or sit around taking memory?

the big deal classes derived control (including tabpage) dispose() method. immune automatic garbage collection, winforms keeps internal table maps handle of control control reference. that's why, say, main form doesn't garbage collected, though program doesn't keep reference it.

adding tabpage tabcontrol's collection takes care of automatic disposal. same applies tabcontrol, added form's controls collection. normal chain of events either program or user closes form. form class iterates child controls , calls dispose() method. tabcontrol same thing in dispose() method, disposing tab pages. windows window gets destroyed in process, removing handle mapping table , allowing garbage collector to, eventually, collect managed wrapper controls.

there nasty trap gets many winforms programmers in trouble. if remove control parent's collection responsibility of disposing yourself. removing not automatically dispose it. winforms keeps native window alive temporarily re-parenting control hidden window named "parking window". nice feature, allows move control 1 parent without having destroy , re-create control.

but keyword there "temporarily". temporarily if next reparent control. gets moved parking window new parent. if don't reparent stay alive ever on parking window. gobbling resources until program terminates. otherwise known leak. can crash program when windows refuses create window when you've created 10,000 of them.

the controlcollection.clear() method harmful here. not dispose controls, moved parking window. if that's not intended, is, you'll have call dispose() on them yourself.


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -