Tag Archives: Garbage Collector

How GC Works

How GC works

The GC maintains lists of managed objects arranged in “generations.” A generation is a measure of the relative lifetime of the objects in memory. The generation number indicates to which generation an object belongs. Recently created objects are stored in lower generations compared to those created earlier in the application’s life cycle. Longer-lived objects get promoted to higher generations.

Because applications tend to create many short-lived objects compared to relatively few long-lived objects, the GC runs much more frequently to clean up objects in the lower generations than in the higher ones.

Finalization is the process, by which the GC allows objects to clean up any unmanaged resources that they’re holding,

Note that you cannot call or override the Finalize method. It is generated implicitly if you have a destructor for the class.

~Test

{

//Necessary cleanup code

}

Dispose method must call GC.SuppressFinalize(this) to prevent the finalizer from running.

public void Dispose()

{

Dispose(true);

GC.SuppressFinalize(this);

}

Finalize Dispose
The execution order of finalize is non-deterministic. It’s execution is deterministic by using call to Dispose() method.
It doesn’t use any interface. It uses IDisposable interface and then override it’s Dispose() method.
you cannot  override the Finalize method, as it is generated implicitly destructor. Dispose is not depended on destructor.
You can suppress Finalize() by using GC.SuppressFinalize(this) You can’t suppress Dispose() as it is not called implicitly.
Advertisements

Leave a comment

Filed under .Net