In my program I add millions of records in a List in a loop, so as the program continues my RAM seems to grow too (I suspect because new and new elements are added to the list) - so if a timer tick event or just button push results in list.Clear(): will this immediately release my RAM? The ram seems to grow a lot to 500mb+ so with limited free amount on amazon instances this is an issue...thanx!
-
1[Fundamentals of garbage collection](https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals) – Filburt Feb 05 '20 at 14:33
-
1Short answer: every object you create gets a adress and a little bit space of your RAM. So, yes it will release RAM, but not *immediately*. You can not be sure that GC has time and ressources are free. – nilsK Feb 05 '20 at 14:37
-
^-- as long as they are managed resources. You have to dispose unmanaged ones – Cid Feb 05 '20 at 14:38
2 Answers
List have Clear() or Remove() methods to clear or Remove the Items within the List. Force the Objects within the List which are not in use, to be cleared. Or Can assign null values to those Objects which are not in use, so that the Null Assigned Objects can Flag the GC that it is not in use and is ready to be Collected.
Assigning List Object to Null after the use, would also help GC to handle it well. ie: myListVariable = null; So that the memory can be cleared by the GC and can be freed from the unused Objects.

- 119
- 3
It's really not recommended, but you can force the garbage collector to run after you've cleared the list?
I found this link: How to force garbage collector to run?
I'd look into implementing the iDisposable interface into your class. This would make it a managed resource and should automatically clear system resources when you're done with the data.
Good luck!

- 116
- 4