Export (0) Print
Expand All

GC.Collect Method ()

Forces garbage collection of all generations.

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

'Declaration
Public Shared Sub Collect
'Usage

GC.Collect
public static void Collect ()
public static function Collect ()

Use this method to attempt to reclaim all memory that is inaccessible. However, the Collect method does not guarantee that all inaccessible memory is reclaimed.

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

Imports System

Namespace GCCollect_Example
    Class MyGCCollectClass
        Private Const maxGarbage As Integer = 1000

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

            'Collect all generations of memory.
            GC.Collect()
            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

package GCCollectExample ; 

import System.* ;

class MyGCCollectClass
{
    private static final int maxGarbage = 1000;

    public static void main(String[] args)
    {
        // Put some objects in memory.
        MyGCCollectClass.MakeSomeGarbage();
        Console.WriteLine("Memory used before collection: {0}", 
            System.Convert.ToString(GC.GetTotalMemory(false)));

        // Collect all generations of memory.
        GC.Collect();
        Console.WriteLine("Memory used after full collection: {0}", 
            System.Convert.ToString(GC.GetTotalMemory(true)));
    } //main

    static void MakeSomeGarbage()
    {
        Version vt;

        for (int i = 0; i < maxGarbage; i++) {
            // Create objects and release them to fill up memory
            // with unused objects.
            vt = new Version();
        }
    } //MakeSomeGarbage
} //MyGCCollectClass

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

Community Additions

ADD
Show:
© 2014 Microsoft