.NET Framework Class Library
GC..::.Collect Method (Int32, GCCollectionMode)

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

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

Visual Basic (Declaration)
Public Shared Sub Collect ( _
    generation As Integer, _
    mode As GCCollectionMode _
)
Visual Basic (Usage)
Dim generation As Integer
Dim mode As GCCollectionMode

GC.Collect(generation, mode)
C#
public static void Collect(
    int generation,
    GCCollectionMode mode
)
Visual C++
public:
static void Collect(
    int generation, 
    GCCollectionMode mode
)
JScript
public static function Collect(
    generation : int, 
    mode : GCCollectionMode
)

Parameters

generation
Type: System..::.Int32
The number of the oldest generation that garbage collection can be performed on.
mode
Type: System..::.GCCollectionMode
One of the GCCollectionMode values.
Exceptions

ExceptionCondition
ArgumentOutOfRangeException

generation is not valid.

-or-

mode is not one of the GCCollectionMode values.

Remarks

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.

Examples

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

Visual Basic
Imports System

Class Program

    Public Shared Sub Main()
        GC.Collect(2, GCCollectionMode.Optimized)
    End Sub
End Class
C#
using System;

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

Windows 7, Windows Vista, Windows XP SP2, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Version Information

.NET Framework

Supported in: 3.5 SP1, 3.0 SP1, 2.0 SP1
See Also

Reference

Other Resources

Tags :


Page view tracker