I built a quick program that needed to loop through an enormous log file (a couple of million records) and find various bits and pieces from inside. Because the volume of data was so huge, I have been curious to watch my Windows Task Manager performance tab and see how much CPU and memory is being used.
After the program successfully gets my results, the CPU usage goes right down, obviously. But after watching my memory usage slowly go up to several gigabytes during execution, it stays the same.
I have tried to call GC.Collect() at the end of my function, tried setting things to null, tried to run the program in Release mode (I heard that GC.Collect() might not work as I want it to in debug mode).
The memory usage goes right down if I close the program, but I can’t figure out why I can’t clean my app up during the apps lifetime. At the end of the day this is a throwaway app, but I’m just curious to know what I’m missing i.e. what is holding on to all this memory.
Thoughts?
The garbage collector is not guaranteed to run when you call Collect(). It simply flags the object for collection. The next time the GC runs it will “collect” the flagged object.
There is no way in .NET to force the GC to collect at a specific point in time – if you need this functionality you’ll need to go to native code.