Lifetime of shared variables

fouzwerg

Member
Joined
Feb 24, 2006
Messages
6
Programming Experience
3-5
Hi,

I have created an ArrayList in my page as shared as it stores information for items in a listbox i have.

This works fine however, when the page is idle say for more than 10 minutes, the array automatically reduces itself in size and loses a lot of the data leading to index out of bounds error (as i try and retrieve info on an item of index listbox.selectedindex).

Is this because of garbage collection removing the objects within my ArrayList? If so, how do I prevent this from happening?

any help would be greatly appreciated

thanks
 
i seriously doubt that, the garbage collector will only 'clean up' object that have been explicitly set to nothing or ones that have gone out of scope. Also by there nature shared variables will exist for the lifetime of the application, which in terms of the garbage collector wil mean that they are instantly promoted to the third generation.
 
hmm yes i had the same thoughts as you but this has led me baffled....


what about the objects within the array... they are just string objects that i add to the list and so only the arrayList is referencing them. Will garbage collection clean those?

Is there a way of ensuring the lifetime of the objects within the arraylist itself and manually destroy when i need to?
 
No variables will be persisted on a page unless you persist them yourself somewhere like in the ViewState, Session or on Disk, or if you re-build those items each time the page loads.

So your ArrayList will be lost as soon as the Page_UnLoad / Finalize is complete (which is called everytime the Response is sent to the user) because your ArrayList is within the scope of that page. ASP.NET does not keep that memory around forever. It will be cleaned up when the GC gets around to it.

My reco would be to either recreate the ArrayList in the Page_Load or Page_PreRender event, or store the ArrayList in the ViewState of the page.

If the ArrayList is expensive in memory, it would probably be best to recreate the ArrayList each time the page loads and clear it in the Unload event of the page. Storing a memory-hungry object in Viewstate or Session is a bad idea because of performance and scalability considerations.
 
Back
Top