Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I have to call GC collect explicitly?

Tags:

c#

.net

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?

like image 625
Venkat Prabhakar Avatar asked Dec 02 '22 19:12

Venkat Prabhakar


1 Answers

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.

like image 162
Theodoros Chatzigiannakis Avatar answered Dec 04 '22 07:12

Theodoros Chatzigiannakis