I have created a sample C# console application, which reads a file data in byte array and converts the byte array to hex string. It requires huge memory and it does not frees the memory after the work is done, I am also nullifying the variables in use.
Here is the sample code:
string filename = @"F:\\AVSEQ09.DAT"; //file size is 32 MB
string hexData = null;
byte[] fileDataContent = File.ReadAllBytes(filename);
if (fileDataContent != null)
hexData = BitConverter.ToString(fileDataContent);
fileDataContent = null;
hexData = null;
//GC.Collect();
Console.ReadKey();
If I run this code it takes 433 MB of private working set and if I uncomment the GC.collect call the memmory comes down to 6 MB. Why do I have to call GC.collect explicitly, is it bad to call GC.collect explicitly, how can I free the memmory (to 6 MB) without calling GC.collect?
Garbage collection is the simulation of infinite memory on a machine with finite memory, by means of recycling memory that a valid program can't notice is missing.
The above is a very important notion because, among others, it highlights the fact that the garbage collector doesn't have to do anything as long as it can provide memory every time your program asks for it.
It may not be the most controllable memory management system, but if your program ends up in a situation under memory pressure, the CLR will usually start a garbage collection cycle automatically to relieve some of that pressure. When the system doesn't seem to be under pressure, the collection is postponed, to avoid frequent unnecessary pauses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With