GC.Collect 方法

定义

强制进行垃圾回收。Forces garbage collection.

重载

Collect()

强制对所有代进行即时垃圾回收。Forces an immediate garbage collection of all generations.

Collect(Int32)

强制对 0 代到指定代进行即时垃圾回收。Forces an immediate garbage collection from generation 0 through a specified generation.

Collect(Int32, GCCollectionMode)

强制在 GCCollectionMode 值所指定的时间对 0 代到指定代进行垃圾回收。Forces a garbage collection from generation 0 through a specified generation, at a time specified by a GCCollectionMode value.

Collect(Int32, GCCollectionMode, Boolean)

在由 GCCollectionMode 值指定的时间,强制对 0 代到指定代进行垃圾回收,另有数值指定回收是否应该为阻碍性。Forces a garbage collection from generation 0 through a specified generation, at a time specified by a GCCollectionMode value, with a value specifying whether the collection should be blocking.

Collect(Int32, GCCollectionMode, Boolean, Boolean)

在由 GCCollectionMode 值指定的时间,强制对 0 代到指定代进行垃圾回收,另有数值指定回收应该为阻碍性还是压缩性。Forces a garbage collection from generation 0 through a specified generation, at a time specified by a GCCollectionMode value, with values that specify whether the collection should be blocking and compacting.

Collect()

强制对所有代进行即时垃圾回收。Forces an immediate garbage collection of all generations.

public:
 static void Collect();
public static void Collect ();
static member Collect : unit -> unit
Public Shared Sub Collect ()

示例

下面的示例演示如何使用 Collect 方法在所有内存代上执行集合。The following example demonstrates how to use the Collect method to perform a collection on all generations of memory. 此代码会生成大量未使用的对象,然后调用 Collect 方法从内存中清理它们。The code generates a number of unused objects, and then calls the Collect method to clean them from memory.

using namespace System;

const int maxGarbage = 1000;

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

void main()
{
   // Put some objects in memory.
   MakeSomeGarbage();
   Console::WriteLine("Memory used before collection:       {0:N0}", 
                      GC::GetTotalMemory( false ) );
   
   // Collect all generations of memory.
   GC::Collect();
   Console::WriteLine("Memory used after full collection:   {0:N0}", 
                      GC::GetTotalMemory( true ) );
}
// The output from the example resembles the following:
//       Memory used before collection:       79,392
//       Memory used after full collection:   52,640
using System;

class MyGCCollectClass
{
   private const int maxGarbage = 1000;

   static void Main()
   {
      // Put some objects in memory.
      MyGCCollectClass.MakeSomeGarbage();
      Console.WriteLine("Memory used before collection:       {0:N0}", 
                        GC.GetTotalMemory(false));
      
      // Collect all generations of memory.
      GC.Collect();
      Console.WriteLine("Memory used after full collection:   {0:N0}", 
                        GC.GetTotalMemory(true));
   }

   static void MakeSomeGarbage()
   {
      Version vt;

      // Create objects and release them to fill up memory with unused objects.
      for(int i = 0; i < maxGarbage; i++) {
         vt = new Version();
      }
   }
}
// The output from the example resembles the following:
//       Memory used before collection:       79,392
//       Memory used after full collection:   52,640
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:N0}", 
                           GC.GetTotalMemory(False))

         'Collect all generations of memory.
         GC.Collect()
         Console.WriteLine("Memory used after full collection:   {0:N0}", 
                           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 
     End Sub
 End Class
' The output from the example resembles the following:
'       Memory used before collection:       79,392
'       Memory used after full collection:   52,640

注解

使用此方法尝试回收所有无法访问的内存。Use this method to try to reclaim all memory that is inaccessible. 它执行所有生成的阻止垃圾回收。It performs a blocking garbage collection of all generations.

所有对象(无论它们处于内存中的时长)都视为集合;但是,不会收集在托管代码中引用的对象。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.

.NET Framework 4.5.1.NET Framework 4.5.1开始,你可以在调用 Collect 方法之前,通过将 GCSettings.LargeObjectHeapCompactionMode 属性设置为 GCLargeObjectHeapCompactionMode.CompactOnce 来压缩大型对象堆(LOH),如下面的示例所示。Starting with the .NET Framework 4.5.1.NET Framework 4.5.1, you can compact the large object heap (LOH) by setting the GCSettings.LargeObjectHeapCompactionMode property to GCLargeObjectHeapCompactionMode.CompactOnce before calling the Collect method, as the following example illustrates.

GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect();      
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce
GC.Collect()      

另请参阅

Collect(Int32)

强制对 0 代到指定代进行即时垃圾回收。Forces an immediate garbage collection from generation 0 through a specified generation.

public:
 static void Collect(int generation);
public static void Collect (int generation);
static member Collect : int -> unit
Public Shared Sub Collect (generation As Integer)

参数

generation
Int32

最后一代进行垃圾回收次数。The number of the oldest generation to be garbage collected.

异常

generation 无效。generation is not valid.

示例

下面的示例演示如何使用 Collect 方法在内存的各个层上执行集合。The following example demonstrates how to use the Collect method to perform a collection on individual layers of memory. 此代码会生成大量未使用的对象,然后调用 Collect 方法从内存中清理它们。The code generates a number of unused objects, and then calls the Collect method to clean them from memory.

using namespace System;
const long maxGarbage = 1000;
ref class MyGCCollectClass
{
public:
   void MakeSomeGarbage()
   {
      Version^ vt;
      for ( int i = 0; i < maxGarbage; i++ )
      {
         
         // Create objects and release them to fill up memory
         // with unused objects.
         vt = gcnew Version;

      }
   }

};

int main()
{
   MyGCCollectClass^ myGCCol = gcnew 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 ) );
}

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();
            }
        }
    }
}
Namespace GCCollectInt_Example
    Class MyGCCollectClass
        Private maxGarbage As Long = 10000

        Public Shared Sub Main()
            Dim myGCCol As 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()

        End Sub


        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

注解

使用此方法尝试回收不可访问的内存。Use this method to try to reclaim memory that is inaccessible. 但是,使用此方法并不保证回收指定代中所有无法访问的内存。However, using this method does not guarantee that all inaccessible memory in the specified generation is reclaimed.

如果实现了对象老化,垃圾回收器不会收集版本号高于指定代的对象。If object aging is implemented, the garbage collector does not collect objects with a generation number that is higher than the specified generation. 如果未实现对象老化,垃圾回收器将在垃圾回收过程中考虑所有对象。If object aging is not implemented, the garbage collector considers all objects during the garbage collection.

使用 MaxGeneration 属性可确定 generation 参数的最大有效值。Use the MaxGeneration property to determine the maximum valid value of the generation parameter.

若要让垃圾回收器考虑所有对象,而不管它们代有哪些,请使用不带任何参数的此方法的版本。To have the garbage collector consider all objects regardless of their generation, use the version of this method that takes no parameters. 若要使垃圾回收器根据 GCCollectionMode 设置回收对象,请使用 GC.Collect(Int32, GCCollectionMode) 方法重载。To have the garbage collector reclaim objects based on a GCCollectionMode setting, use the GC.Collect(Int32, GCCollectionMode) method overload.

另请参阅

Collect(Int32, GCCollectionMode)

强制在 GCCollectionMode 值所指定的时间对 0 代到指定代进行垃圾回收。Forces a garbage collection from generation 0 through a specified generation, at a time specified by a GCCollectionMode value.

public:
 static void Collect(int generation, GCCollectionMode mode);
public static void Collect (int generation, GCCollectionMode mode);
static member Collect : int * GCCollectionMode -> unit
Public Shared Sub Collect (generation As Integer, mode As GCCollectionMode)

参数

generation
Int32

最后一代进行垃圾回收次数。The number of the oldest generation to be garbage collected.

mode
GCCollectionMode

一个枚举值,指定垃圾回收是强制进行(DefaultForced)还是优化 (Optimized)。An enumeration value that specifies whether the garbage collection is forced (Default or Forced) or optimized (Optimized).

异常

generation 无效。generation is not valid.

- 或 --or- mode 不是 GCCollectionMode 值之一。mode is not one of the GCCollectionMode values.

示例

下面的示例使用 Optimized 设置强制执行第2代对象的垃圾回收。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);
    }
}
Class Program

    Public Shared Sub Main()
        GC.Collect(2, GCCollectionMode.Optimized)
    End Sub
End Class

注解

使用 mode 参数可指定垃圾回收应立即发生还是仅在回收对象的最佳时间时进行。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.

若要在应用程序的关键期间调整垃圾回收的侵入性,请设置 LatencyMode 属性。To adjust the intrusiveness of garbage collection during critical periods in your application, set the LatencyMode property.

垃圾回收器不会收集版本号高于 generation 参数指定的代数的对象。The garbage collector does not collect objects with a generation number higher than specified by the generation parameter. 使用 MaxGeneration 属性可确定 generation的最大有效值。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.

若要使垃圾回收器将对象回收到指定的对象代,请使用 GC.Collect(Int32) 方法重载。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.

另请参阅

Collect(Int32, GCCollectionMode, Boolean)

在由 GCCollectionMode 值指定的时间,强制对 0 代到指定代进行垃圾回收,另有数值指定回收是否应该为阻碍性。Forces a garbage collection from generation 0 through a specified generation, at a time specified by a GCCollectionMode value, with a value specifying whether the collection should be blocking.

public:
 static void Collect(int generation, GCCollectionMode mode, bool blocking);
public static void Collect (int generation, GCCollectionMode mode, bool blocking);
static member Collect : int * GCCollectionMode * bool -> unit
Public Shared Sub Collect (generation As Integer, mode As GCCollectionMode, blocking As Boolean)

参数

generation
Int32

最后一代进行垃圾回收次数。The number of the oldest generation to be garbage collected.

mode
GCCollectionMode

一个枚举值,指定垃圾回收是强制进行(DefaultForced)还是优化 (Optimized)。An enumeration value that specifies whether the garbage collection is forced (Default or Forced) or optimized (Optimized).

blocking
Boolean

true 执行阻碍性垃圾回收;false 在可能的情况下执行后台垃圾回收。true to perform a blocking garbage collection; false to perform a background garbage collection where possible.

异常

generation 无效。generation is not valid.

- 或 --or- mode 不是 GCCollectionMode 值之一。mode is not one of the GCCollectionMode values.

注解

下表总结了 modeblocking 参数的交互:The following table summarizes the interaction of the mode and blocking parameters:

mode blockingtrueblocking is true blockingfalseblocking is false
ForcedDefaultForced or Default 尽快执行阻塞回收。A blocking collection is performed as soon as possible. 如果后台回收正在进行,并且 generation 为0或1,则 Collect(Int32, GCCollectionMode, Boolean) 方法会立即触发阻止回收,并在回收完成后返回。If a background collection is in progress and generation is 0 or 1, the Collect(Int32, GCCollectionMode, Boolean) method immediately triggers a blocking collection and returns when the collection is finished. 如果后台回收正在进行,并且 generation 为2,则该方法将一直等待,直到后台收集完成,触发一个阻止第2代回收,然后返回。If a background collection is in progress and generation is 2, the method waits until the background collection is finished, triggers a blocking generation 2 collection, and then returns. 尽快执行回收。A collection is performed as soon as possible. Collect(Int32, GCCollectionMode, Boolean) 方法请求执行后台回收,但这并没有保证;阻止式回收仍可执行,具体视环境而定。The Collect(Int32, GCCollectionMode, Boolean) method requests a background collection, but this is not guaranteed; depending on the circumstances, a blocking collection may still be performed. 如果后台回收正在进行,该方法将立即返回。If a background collection is already in progress, the method returns immediately.
Optimized 可能会执行阻止式回收,具体视垃圾回收器的状态和 generation 参数而定。A blocking collection may be performed, depending on the state of the garbage collector and the generation parameter. 垃圾回收器会尽量提供最佳性能。The garbage collector tries to provide optimal performance. 根据垃圾回收器的状态,有时可执行回收。A collection may be performed, depending on the state of the garbage collector. Collect(Int32, GCCollectionMode, Boolean) 方法请求执行后台回收,但这并没有保证;阻止式回收仍可执行,具体视环境而定。The Collect(Int32, GCCollectionMode, Boolean) method requests a background collection, but this is not guaranteed; depending on the circumstances, a blocking collection may still be performed. 垃圾回收器会尽量提供最佳性能。The garbage collector tries to provide optimal performance. 如果后台回收正在进行,该方法将立即返回。If a background collection is already in progress, the method returns immediately.

如果调用 Collect(Int32, GCCollectionMode, Boolean) 方法会执行完全阻止性垃圾回收,还可以通过在调用 Collect 方法之前将 GCSettings.LargeObjectHeapCompactionMode 属性设置为 GCLargeObjectHeapCompactionMode.CompactOnce 来压缩大型对象堆。If a call to the Collect(Int32, GCCollectionMode, Boolean) method performs a full blocking garbage collection, you can also compact the large object heap by setting the GCSettings.LargeObjectHeapCompactionMode property to GCLargeObjectHeapCompactionMode.CompactOnce before calling the Collect method.

Collect(Int32, GCCollectionMode, Boolean, Boolean)

在由 GCCollectionMode 值指定的时间,强制对 0 代到指定代进行垃圾回收,另有数值指定回收应该为阻碍性还是压缩性。Forces a garbage collection from generation 0 through a specified generation, at a time specified by a GCCollectionMode value, with values that specify whether the collection should be blocking and compacting.

public:
 static void Collect(int generation, GCCollectionMode mode, bool blocking, bool compacting);
public static void Collect (int generation, GCCollectionMode mode, bool blocking, bool compacting);
static member Collect : int * GCCollectionMode * bool * bool -> unit
Public Shared Sub Collect (generation As Integer, mode As GCCollectionMode, blocking As Boolean, compacting As Boolean)

参数

generation
Int32

最后一代进行垃圾回收次数。The number of the oldest generation to be garbage collected.

mode
GCCollectionMode

一个枚举值,指定垃圾回收是强制进行(DefaultForced)还是优化 (Optimized)。An enumeration value that specifies whether the garbage collection is forced (Default or Forced) or optimized (Optimized).

blocking
Boolean

true 执行阻碍性垃圾回收;false 在可能的情况下执行后台垃圾回收。true to perform a blocking garbage collection; false to perform a background garbage collection where possible.

compacting
Boolean

true 表示压缩小对象堆;false 表示仅进行清理。true to compact the small object heap; false to sweep only.

注解

如果 false``blocking,GC 将决定是执行后台还是阻止垃圾回收。If blocking is false, the GC decides whether to perform a background or a blocking garbage collection. 如果 true``compacting,则会执行阻止性垃圾回收。If compacting is true, it performs a blocking garbage collection.

如果 true``compacting,则运行时将压缩小对象堆(SOH)。If compacting is true, the runtime compacts the small object heap (SOH). 不会压缩大型对象堆(LOH),除非 GCSettings.LargeObjectHeapCompactionMode 属性设置为 GCLargeObjectHeapCompactionMode.CompactOnceThe large object heap (LOH) is not compacted unless the GCSettings.LargeObjectHeapCompactionMode property is set to GCLargeObjectHeapCompactionMode.CompactOnce. 请注意,这包括所有阻碍性垃圾回收,而不只是完全阻止垃圾回收。Note that this includes all blocking garbage collections, not just full blocking garbage collections.

可以调用 Collect(Int32, GCCollectionMode, Boolean, Boolean) 方法,将托管堆减小到可能的最小大小,如以下代码片段所示。You can call the Collect(Int32, GCCollectionMode, Boolean, Boolean) method to reduce the managed heap to the smallest size possible, as the following code fragment illustrates.

GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect(2, GCCollectionMode.Forced, true, true);
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce
GC.Collect(2, GCCollectionMode.Forced, True, True)

指定 compacting 参数 true 可保证压缩、完全阻碍性垃圾回收。Specifying true for the compacting argument guarantees a compacting, full blocking garbage collection. GCSettings.LargeObjectHeapCompactionMode 属性设置为 GCLargeObjectHeapCompactionMode.CompactOnce 可确保对 LOH 和 SOH 进行压缩。Setting the GCSettings.LargeObjectHeapCompactionMode property to GCLargeObjectHeapCompactionMode.CompactOnce ensures that both the LOH and SOH are compacted.

适用于