System.GC Class

Assembly: Mscorlib.dll
Namespace: System
Summary
Controls the system garbage collector, a service that automatically reclaims unused memory.
C# Syntax:
public sealed class GC
Remarks
The methods in this class influence when an object is garbage collected and when resources allocated by an object are released. Properties in this class provide information about the total amount of memory available in the system and the age category, or generation, of memory allocated to an object.

The garbage collector tracks and reclaims objects allocated in managed memory. Periodically, the garbage collector performs garbage collection to reclaim memory allocated to objects for which there are no valid references. Garbage collection happens automatically when a request for memory cannot be satisfied using available free memory. Alternatively, an application can force garbage collection using the GC.Collect method.

Garbage collection consists of the following steps:

  1. The garbage collector searches for managed objects that are referenced in managed code.
  2. The garbage collector attempts to finalize objects that are not referenced.
  3. The garbage collector frees objects that are not referenced and reclaims their memory.

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 might free objects that are being used exclusively in unmanaged code unless explicitly prevented from doing so. The GC.KeepAlive method provides a mechanism that prevents the garbage collector from collecting objects that are still in use in unmanaged code.

Other than managed memory allocations, implementations of the garbage collector do 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 can 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 can implement the IDisposable interface, which contains the IDisposable.Dispose method that performs 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.

It is recommended, but not required, that garbage collectors support object aging using generations. A generation is a unit of measure of the relative age of objects in memory. The generation number, or age, of an object tells which generation an object belongs to. Objects created more recently are part of newer generations, and have lower generation numbers than objects created earlier in the application life cycle. Objects in the most recent generation are in generation zero.



Notes to implementors: This implementation of the garbage collector supports three generations. GC.MaxGeneration is used to determine the maximum generation number supported by the system. Object aging allows applications to target garbage collection at a specific set of generations rather than requiring the garbage collector to evaluate all generations.
See also:
System Namespace

System.GC Member List:

Public Properties
MaxGeneration Read-only

Gets the maximum number of generations the system currently supports.
Public Methods
Collect Overloaded:
Collect()

Forces garbage collection of all generations.
Collect Overloaded:
Collect(int generation)

Forces garbage collection from generation zero through a specified generation.
Equals
(inherited from System.Object)
See base class member description: System.Object.Equals

Derived from System.Object, the primary base class for all objects.
GetGeneration Overloaded:
GetGeneration(object obj)

Returns the current generation number of the specified object.
GetGeneration Overloaded:
GetGeneration(WeakReference wo)

Returns the current generation number of the target of a specified weak reference.
GetHashCode
(inherited from System.Object)
See base class member description: System.Object.GetHashCode

Derived from System.Object, the primary base class for all objects.
GetTotalMemory Retrieves the number of bytes currently thought to be allocated. A parameter indicates whether this method can wait a short interval before returning while the system collects garbage and finalizes objects.
GetType
(inherited from System.Object)
See base class member description: System.Object.GetType

Derived from System.Object, the primary base class for all objects.
KeepAlive References the specified object, making it ineligible for garbage collection from the start of the current routine to the point where this method is called.
ReRegisterForFinalize Requests that the system call the finalizer method for the specified object, for which GC.SuppressFinalize has previously been called.
SuppressFinalize Requests that the system not call the finalizer method for the specified object.
ToString
(inherited from System.Object)
See base class member description: System.Object.ToString

Derived from System.Object, the primary base class for all objects.
WaitForPendingFinalizers Suspends the current thread until the thread processing the queue of finalizers has emptied that queue.
Protected Methods
Finalize
(inherited from System.Object)
See base class member description: System.Object.Finalize

Derived from System.Object, the primary base class for all objects.
MemberwiseClone
(inherited from System.Object)
See base class member description: System.Object.MemberwiseClone

Derived from System.Object, the primary base class for all objects.

Hierarchy:


System.GC Member Details

Property: MaxGeneration (read-only)
Summary
Gets the maximum number of generations the system currently supports.
C# Syntax:
public static int MaxGeneration {get;}
Remarks
The generation number, or age, of an object is an implementation-defined relative measure of an object's lifespan. The most recently created objects are in generation zero and the oldest objects are in a generation less than or equal to the generation returned by the GC.MaxGeneration property.

The garbage collector assumes that newer memory is more likely to be eligible for garbage collection than older memory. Therefore, the garbage collector improves its performance by adjusting generation numbers each time it reclaims memory, and the GC.MaxGeneration property value can grow over time.

If object aging is implemented, the GC.MaxGeneration property returns the maximum generation number used by the system; otherwise, this property returns zero.



Notes to implementors: For this implementation, the value returned by the GC.MaxGeneration property is guaranteed to remain constant for the lifetime of an executing application.

Use the GC.MaxGeneration property to determine the maximum value you can specify when calling the GC.Collect method that takes a generation parameter.

See also:
GC.GetGeneration

Return to top


Overloaded Method: Collect()
Summary
Forces garbage collection of all generations.
C# Syntax:
public static void Collect();
Remarks
Use this method to attempt to reclaim all memory that is inaccessible. However, the GC.Collect method does not guarantee that all inaccessible memory is reclaimed.

All objects, regardless of how long they have been in memory, are considered for collection; however, objects that are referenced in managed code are not collected. Use this method to force the system to attempt to reclaim the maximum amount of available memory.

Return to top


Overloaded Method: Collect(
   int generation
)
Summary
Forces garbage collection from generation zero through a specified generation.
C# Syntax:
public static void Collect(
   int generation
);
Parameters:

generation

The maximum garbage-collected generation.

Exceptions
Exception Type Condition
ArgumentOutOfRangeException generation is less than zero or greater than the number of generations that exist.
Remarks
Use this method to attempt to reclaim memory that is inaccessible. However, it does not guarantee that all inaccessible memory in the specified generation is reclaimed.

If object aging is implemented, the garbage collector does not collect objects with a generation number higher than the specified generation. If object aging is not implemented, the garbage collector considers all objects during the garbage collection.

Use the GC.MaxGeneration property to determine the maximum valid value of generation.

To have the garbage collector consider all objects regardless of their generation, use the version of this method that takes no arguments.

Return to top


Method: Equals(
   object obj
)
Inherited
See base class member description: System.Object.Equals
C# Syntax:
public virtual bool Equals(
   object obj
);

For more information on members inherited from System.Object click on the link above.

Return to top


Method: Finalize()
Inherited
See base class member description: System.Object.Finalize
C# Syntax:
~GC();

For more information on members inherited from System.Object click on the link above.

Return to top


Overloaded Method: GetGeneration(
   object obj
)
Summary
Returns the current generation number of the specified object.
C# Syntax:
public static int GetGeneration(
   object obj
);
Parameters:

obj

The object for which generation information is retrieved.

Return Value:
The current generation number of obj.
Remarks
Use this method to determine the age of an object, then use that information with the GC.Collect method to force the garbage collector to collect objects in the same generation. For example, use this method when you have a set of objects that are created as a group and become inaccessible at the same time.
See also:
GC.MaxGeneration

Return to top


Overloaded Method: GetGeneration(
   WeakReference wo
)
Summary
Returns the current generation number of the target of a specified weak reference.
C# Syntax:
public static int GetGeneration(
   WeakReference wo
);
Parameters:

wo

The weak reference of a target.

Return Value:
The current generation number of the target of wo.
Exceptions
Exception Type Condition
ArgumentException wo has already been garbage collected.
See also:
GC.MaxGeneration

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Object.GetHashCode
C# Syntax:
public virtual int GetHashCode();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetTotalMemory(
   bool forceFullCollection
)
Summary
Retrieves the number of bytes currently thought to be allocated. A parameter indicates whether this method can wait a short interval before returning while the system collects garbage and finalizes objects.
C# Syntax:
public static long GetTotalMemory(
   bool forceFullCollection
);
Parameters:

forceFullCollection

A Boolean value that, if true, indicates this method can wait awhile for garbage collection before returning.

Return Value:
A number that is the best available approximation of the number of bytes currently allocated in managed memory.
Remarks
If forceFullCollection is true, this method waits a short interval before returning while the system collects garbage and finalizes objects. The duration of the interval is an internally specified limit determined by the number of garbage collection cycles completed and the change in the amount of memory recovered between cycles. The garbage collector does not guarantee that all inaccessible memory is collected.

Return to top


Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: KeepAlive(
   object obj
)
Summary
References the specified object, making it ineligible for garbage collection from the start of the current routine to the point where this method is called.
C# Syntax:
public static void KeepAlive(
   object obj
);
Parameters:

obj

The object to reference.

Remarks
The purpose of the GC.KeepAlive method is to ensure the existence of a reference to an object that is at risk of being prematurely reclaimed by the garbage collector. A common scenario where this might happen is when there are no references to the object in managed code or data but the object is still in use in unmanaged code, such as Win32 APIs, unmanaged DLLs, or methods using COM.

This method references obj, making that object ineligible for garbage collection from the start of the routine to the point, in execution order, where this method is called. Code this method at the end, not the beginning, of the range of instructions where obj must be available.

The implementation of the GC.KeepAlive method is intentionally hidden, which prevents mechanisms such as optimizing compilers from omitting this method from the compiled code, and garbage collection from determining whether obj is no longer in use. This method performs no operations and produces no side effects.

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: ReRegisterForFinalize(
   object obj
)
Summary
Requests that the system call the finalizer method for the specified object, for which GC.SuppressFinalize has previously been called.
C# Syntax:
public static void ReRegisterForFinalize(
   object obj
);
Parameters:

obj

The object for which a finalizer must be called.

Exceptions
Exception Type Condition
ArgumentNullException obj is null.
InvalidOperationException This method is not called within a property, method, or constructor.
Remarks
The GC.ReRegisterForFinalize method adds obj to the list of objects that request finalization before the garbage collector frees the object. The obj parameter must be the caller of this method.

Calling the GC.ReRegisterForFinalize method does not guarantee that the garbage collector will call an object's finalizer.

By default, all objects that implement finalizers are added to the list of objects that require finalization; however, an object might have already been finalized, or might have disabled finalization by calling the GC.SuppressFinalize method.

A finalizer can use this method to resurrect itself or an object it references.

.NET Framework Security:
SecurityPermission for calling unmanaged code. Associated enumeration: SecurityPermissionFlag.UnmanagedCode.
See also:
GC.SuppressFinalize

Return to top


Method: SuppressFinalize(
   object obj
)
Summary
Requests that the system not call the finalizer method for the specified object.
C# Syntax:
public static void SuppressFinalize(
   object obj
);
Parameters:

obj

The object for which a finalizer must not be called.

Exceptions
Exception Type Condition
ArgumentNullException obj is null.
ExecutionEngineException This method is not called within a property, method, or constructor.
Remarks
The method removes obj from the set of objects that require finalization. The obj parameter is required to be the caller of this method.

Objects that implement the IDisposable interface can call this method from the IDisposable.Dispose method to prevent the garbage collector from calling Object.Finalize on an object that does not require it.

.NET Framework Security:
SecurityPermission for calling unmanaged code. Associated enumeration: SecurityPermissionFlag.UnmanagedCode.
See also:
GC.ReRegisterForFinalize

Return to top


Method: ToString()
Inherited
See base class member description: System.Object.ToString
C# Syntax:
public virtual string ToString();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: WaitForPendingFinalizers()
Summary
Suspends the current thread until the thread processing the queue of finalizers has emptied that queue.
C# Syntax:
public static void WaitForPendingFinalizers();
Remarks
When the garbage collector finds objects that can be reclaimed, it checks each object to determine the object's finalization requirements. If an object implements a finalizer and has not disabled finalization by calling GC.SuppressFinalize, the object is passed to the thread that handles finalization. This method blocks until all finalizers have run to completion.

Finalizers are run on a separate thread of execution, so there is no guarantee that this method will terminate. However, this thread can be interrupted by another thread while the GC.WaitForPendingFinalizers method is in progress. For example, you can start another thread that waits for a period of time then interrupts this thread if this thread is still suspended.

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.