GC.Collect GC.Collect GC.Collect GC.Collect Method

定义

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

重载

Collect() Collect() Collect() Collect()

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

Collect(Int32) Collect(Int32) Collect(Int32) Collect(Int32)

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

Collect(Int32, GCCollectionMode) Collect(Int32, GCCollectionMode) Collect(Int32, GCCollectionMode) 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) Collect(Int32, GCCollectionMode, Boolean) Collect(Int32, GCCollectionMode, Boolean) 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) Collect(Int32, GCCollectionMode, Boolean, Boolean) Collect(Int32, GCCollectionMode, Boolean, Boolean) 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() Collect() Collect() 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,您可以通过设置压缩大型对象堆 (LOH)GCSettings.LargeObjectHeapCompactionMode属性设置为GCLargeObjectHeapCompactionMode.CompactOnce之前,调用Collect方法,如下面的示例说明了。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) Collect(Int32) Collect(Int32) 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 Int32 Int32 Int32

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

异常

示例

下面的示例演示如何使用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();
            }
        }
    }
}
Imports System

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) Collect(Int32, GCCollectionMode) Collect(Int32, GCCollectionMode) 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 Int32 Int32 Int32

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

mode
GCCollectionMode GCCollectionMode GCCollectionMode 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.

示例

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

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属性来确定有效的最大值generationUse 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) Collect(Int32, GCCollectionMode, Boolean) Collect(Int32, GCCollectionMode, Boolean) 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 Int32 Int32 Int32

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

mode
GCCollectionMode GCCollectionMode GCCollectionMode GCCollectionMode

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

blocking
Boolean Boolean Boolean 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)方法执行完整的阻碍性垃圾回收时,您还可以通过设置压缩大型对象堆GCSettings.LargeObjectHeapCompactionMode属性设置为GCLargeObjectHeapCompactionMode.CompactOnce之前,调用Collect方法。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) Collect(Int32, GCCollectionMode, Boolean, Boolean) Collect(Int32, GCCollectionMode, Boolean, Boolean) 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 Int32 Int32 Int32

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

mode
GCCollectionMode GCCollectionMode GCCollectionMode GCCollectionMode

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

blocking
Boolean Boolean Boolean Boolean

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

compacting
Boolean Boolean Boolean Boolean

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

注解

如果blockingfalse,GC 决定是否要执行后台任务或阻碍性垃圾回收。If blocking is false, the GC decides whether to perform a background or a blocking garbage collection. 如果compactingtrue,它执行阻碍性垃圾回收。If compacting is true, it performs a blocking garbage collection.

如果compactingtrue,运行时将压缩小对象堆 (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)

指定truecompacting参数可保证压缩、 完整的阻碍性垃圾回收。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.

适用于