Collect Method
Collapse the table of content
Expand the table of content

GC.Collect Method

Forces an immediate garbage collection of all generations.

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

Public Shared Sub Collect

Use this method to try to reclaim all memory that is inaccessible.

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 try to reclaim the maximum amount of available memory.

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

Imports System

Namespace GCCollect_Example
    Class MyGCCollectClass
        Private Const maxGarbage As Integer = 1000

        Shared Sub Main()
            'Put some objects in memory.
            Console.WriteLine("Memory used before collection: {0}", GC.GetTotalMemory(False))

            'Collect all generations of memory.
            Console.WriteLine("Memory used after full collection: {0}", GC.GetTotalMemory(True))
        End Sub 

        Shared Sub MakeSomeGarbage()
            Dim vt As Version

            Dim i As Integer 
            For i = 0 To maxGarbage - 1
                'Create objects and release them to fill up memory 
                'with unused objects.
                vt = New Version()
            Next i
        End Sub 
    End Class 
End Namespace

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

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.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

XNA Framework

Supported in: 3.0, 2.0, 1.0

Community Additions

© 2015 Microsoft