GC.Collect Method (Int32)


Forces an immediate garbage collection from generation 0 through a specified generation.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)

static member Collect : 
        generation:int -> unit


Type: System.Int32

The number of the oldest generation to be garbage collected.

Exception Condition

generation is not valid.

Use this method to try to reclaim memory that is inaccessible. However, using this method 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 that is higher than the specified generation. If object aging is not implemented, the garbage collector considers all objects during the garbage collection.

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

To have the garbage collector consider all objects regardless of their generation, use the version of this method that takes no parameters. To have the garbage collector reclaim objects based on a GCCollectionMode setting, use the GC.Collect(Int32, GCCollectionMode) method overload.

The following example demonstrates how to use the Collect method to perform a collection on individual layers of memory. The code generates a number of unused objects, and then calls the Collect method to clean them from memory.

No code example is currently available or this language may not be supported.

Universal Windows Platform
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Windows Phone Silverlight
Available since 7.1
Windows Phone
Available since 8.1
Return to top