How to free Generic list object memory in C#
In my Silverlight application I have created a generic list object with a custom class. I have approximately 3lacs (300,000) records in it. I have to bi开发者_C百科nd different data to the same list frequently, but sometimes I get a out of memory error.
How do I free the memory of generic list of a custom class in C#.NET.
Only store what you need to in the List
.
I think, that it's enough, that you remove the unused Items from the List. So the List isn't growing to 300,000 Records.
If no reference is set to an object (ReferenceCounter == 0) the gc will collect it,... in the future...
So i think your main Questions should be, what do you want to do with more than 300,000 entries and is it nessesary to hold them all?
If yes: Maybe a Proxy or Flyweight pattern would solve your Problem with ease. Due to the LazyLoading of the heavy Objects you can hold the List of small Objekts, which only loads their heavy content by explicit call to do so.
Now it comes better, with the Flyweight pattern you can also store some basic Information (e.g. MetaData), for example of an Image, the Size, without loading the full heavy image.
So if you can't reduce your Listentry count, just reduce the MemoryFootprint of your Objects.
p.s.: The Flyweights could also forgett their heavy Objects after a defined time to shrink after a defined sleeping time.
Clear the list and run GC.Collect();
twice.
If I remember correctly, the first time the GC passes an unreferenced item it marks it for garbage collection, the second time it passes it removes it from memory. (If I'm wrong, please let me know.)
There is still no guarantee that the memory will be cleared but it's as close as you can get afaik.
精彩评论