System.GC.Collect 方法 (Int32)

方法描述

强制对零代到指定代进行即时垃圾回收。

语法定义(C# System.GC.Collect 方法 (Int32) 的用法)

public static void Collect(
	int generation
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
generation System-Int32 可执行垃圾回收的最早的代的编号。
返回值 void

提示和注释

使用此方法尝试回收无法访问的内存。 然而,使用此方法并不保证可以回收指定代中所有无法访问的内存。

如果实现对象老化,则垃圾回收器不会回收代编号高于所指定代的对象。 如果没有实现对象老化,则垃圾回收器将在垃圾回收期间考虑所有对象。

使用 MaxGeneration 属性确定 generation 参数的最大有效值。

若要让垃圾回收器考虑所有对象而不管它们所在的代,请使用此方法的无参数版本。 若要让垃圾回收器根据 GCCollectionMode 设置回收对象,请使用 GC.Collect(Int32, GCCollectionMode) 方法重载。

System.GC.Collect 方法 (Int32)例子

代码将生成许多未使用的对象,然后调用 Collect 方法从内存中清理这些对象。

using System;

namespace GCCollectIntExample
{
    class MyGCCollectClass
    {
        private const long maxGarbage = 1000;

        static void Main()
        {
            MyGCCollectClass myGCCol = new MyGCCollectClass();

            // Determine the maximum number of generations the system
	    // garbage collector currently supports.
            Console.WriteLine("The highest generation is {0}", GC.MaxGeneration);

            myGCCol.MakeSomeGarbage();

            // Determine which generation myGCCol object is stored in.
            Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol));

            // Determine the best available approximation of the number 
	    // of bytes currently allocated in managed memory.
            Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(false));

            // Perform a collection of generation 0 only.
            GC.Collect(0);

            // Determine which generation myGCCol object is stored in.
            Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol));

            Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(false));

            // Perform a collection of all generations up to and including 2.
            GC.Collect(2);

            // Determine which generation myGCCol object is stored in.
            Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol));
            Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(false));
            Console.Read();
        }

        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();
            }
        }
    }
}

异常

异常 异常描述
ArgumentOutOfRangeException generation 无效。

命名空间

namespace: System

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。