System Namespace

Class GC

Represents the garbage collector, which determines the lifetime of objects in managed code.

Namespace: System

Assembly: mscorlib (in mscorlib.dll)

Syntax

public static class GC

Remarks

The garbage collector automatically manages memory in .NET applications. You typically do not need to manually allocate or deallocate memory. The GC class provides methods to interact with the garbage collector, such as requesting a collection or querying information about the collection process.

Note: While the GC automates memory management, understanding its behavior can be crucial for optimizing performance and debugging memory leaks in complex applications.

Methods

Method Details

Collect()

public static void Collect()

Forces a full garbage collection of all generations. This method is a blunt instrument and should be used sparingly, as it can pause application execution.

Collect(int generation)

public static void Collect(int generation)
Parameters
Name Description Type
generation The generation to collect. Must be between 0 and 3, inclusive. System.Int32

Forces a garbage collection of the specified generation and all generations prior to it. For example, calling Collect(1) will collect generations 0 and 1. The maximum generation is typically 2 (or 3 in some older .NET Framework versions).

GetTotalMemory(bool forceFullCollection)

public static long GetTotalMemory(bool forceFullCollection)
Parameters
Name Description Type
forceFullCollection true to specify that the garbage collector should run a full collection before returning the memory count; otherwise, false. System.Boolean

Returns the approximate amount of memory currently in use by the .NET runtime. If forceFullCollection is true, the GC will perform a full collection first to ensure the most accurate measurement possible. This value is returned in bytes.

RegisterForFullCollectionNotification(int maxGenerations, WaitCallback callBack)

public static bool RegisterForFullCollectionNotification(int maxGenerations, WaitCallback callBack)
Parameters
Name Description Type
maxGenerations The maximum generation number to monitor for full collection notifications. System.Int32
callBack A WaitCallback delegate that represents the method to be called when the garbage collector is about to perform a full collection. System.Threading.WaitCallback

Registers a callback delegate to be invoked when the garbage collector is about to perform a full collection up to the specified maximum generation. This can be useful for performing cleanup or logging before objects are finalized.

Tip: Use this method cautiously, as registering too many callbacks or performing lengthy operations within the callback can impact GC performance.

Related Topics