See Also: GC Members
The garbagecollector is responsible for tracking and reclaiming objects allocated in managed memory. Periodically, the garbage collector performs a garbage collection to reclaim memory allocated to objects for which there are no valid references. Garbage collections happen automatically when a request for memory cannot be satisfied using available free memory.
A garbage collection consists of the following steps:
During a collection, the garbage collector will not free an object if it finds one or more references to the object in managed code. However, the garbage collector does not recognize references to an object from unmanaged code, and can free objects that are being used exclusively in unmanaged code unless explicitly prevented from doing so. The GC.KeepAlive(object) method provides a mechanism that prevents the garbage collector from collecting objects that are still in use in unmanaged code.
Implementations of the garbage collector should track the following information:
Other than managed memory allocations, implementations of the garbage collector should not maintain information about resources held by an object, such as file handles or database connections. When a type uses unmanaged resources that must be released before instances of the type are reclaimed, the type should implement a finalizer . In most cases, finalizers are implemented by overriding the object.Finalize method; however, types written in C# or C++ implement destructors, which compilers turn into an override of object.Finalize.
In most cases, if an object has a finalizer, the garbage collector calls it prior to freeing the object. However, the garbage collector is not required to call finalizers in all situations. Also, the garbage collector is not required to use a specific thread to finalize objects, or guarantee the order in which finalizers are called for objects that reference each other but are otherwise available for garbage collection.
In scenarios where resources must be released at a specific time, classes should implement the IDisposable interface, which contains a single method (IDisposable.Dispose) that is used to perform resource management and cleanup tasks. Classes that implement IDisposable.Dispose must specify, as part of their class contract, if and when class consumers call the method to clean up the object. The garbage collector does not, by default, call the IDisposable.Dispose method; however, implementations of the IDisposable.Dispose method can call methods in the GC class to customize the finalization behavior of the garbage collector.