The garbage collector in .Net takes care of bulk of the
memory management responsibility, freeing up the developer to focus on core
issues. The garbage collector is optimized to perform the memory free-up at the
best time based upon the allocations being made. Up until now two
techniques have been used on the Windows platform for deallocating
memory that processes have dynamically requested from the system:
·
Make the application code do it all manually.
·
Make objects maintain reference counts.
Having the application code responsible for deallocating memory is the technique used by lower-level,
high-performance languages such as C++. It is efficient, and it has the
advantage that resources are never occupied for longer than necessary. The big
disadvantage, however, is the frequency of errors. Code that requests memory
also should explicitly inform the system when it no longer requires that
memory. However, it is easy to overlook this, resulting in memory leaks.
The .NET runtime relies on the garbage collector instead.
This is a program whose purpose is to clean up memory. The idea is that all
dynamically requested memory is allocated on the heap, which is true for all
languages, although in the case of .NET, the CLR maintains its own managed heap
for .NET applications to use. When .NET detects that the managed heap for a
given process is becoming full and therefore needs tidying up, it calls the
garbage collector. The garbage collector runs through variables currently in
scope in code, examining references to objects stored on the heap to identify
which ones are accessible from the code—that is to say which objects have
references that refer to them. Any objects that are not referred to are deemed
to be no longer accessible from your code and can therefore be removed.
One important aspect of garbage collection is that we cannot
guarantee when the garbage collector will be called; it will be called when the
CLR decides that it is needed, unless we explicitly call the collector, though
it is also possible to override this process and call up the garbage collector
in our code.
To call garbage collector in our code we can force garbage
collection by invoking the GC.Collect method from the
program.
The System.GC class provides methods that control
the system garbage collector.