Collect Method (Int32, GCCollectionMode)

GC.Collect Method (Int32, GCCollectionMode)


Forces a garbage collection from generation 0 through a specified generation, at a time specified by a GCCollectionMode value.

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

public static void Collect(
	int generation,
	GCCollectionMode mode


Type: System.Int32

The number of the oldest generation to be garbage collected.

Type: System.GCCollectionMode

An enumeration value that specifies whether the garbage collection is forced (GCCollectionMode.Default or GCCollectionMode.Forced) or optimized (GCCollectionMode.Optimized).

Exception Condition

generation is not valid.


mode is not one of the GCCollectionMode values.

Use the mode parameter to specify whether garbage collection should occur immediately or only if the time is optimal to reclaim objects. Using this method does not guarantee that all inaccessible memory in the specified generation is reclaimed.

To adjust the intrusiveness of garbage collection during critical periods in your application, set the LatencyMode property.

The garbage collector does not collect objects with a generation number higher than specified by the generation parameter. Use the 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 parameters.

To have the garbage collector reclaim objects up to a specified generation of objects, use the GC.Collect(Int32) method overload. When you specify the maximum generation, all objects are collected.

The following example forces a garbage collection for generation 2 objects with the Optimized setting.

using System;

class Program
    static void Main(string[] args)
        GC.Collect(2, GCCollectionMode.Optimized);

Universal Windows Platform
Available since 4.5
.NET Framework
Available since 2.0
Portable Class Library
Supported in: portable .NET platforms
Windows Phone Silverlight
Available since 8.0
Windows Phone
Available since 8.1
Return to top
© 2015 Microsoft