GC GC GC GC Class

定义

控制系统垃圾回收器(一种自动回收未使用内存的服务)。Controls the system garbage collector, a service that automatically reclaims unused memory.

public ref class GC abstract sealed
public static class GC
type GC = class
Public Class GC
继承

示例

以下示例使用多个 GC 方法以获取生成和内存块未使用的对象有关的信息并将其打印到控制台。The following example uses several GC methods to get generation and memory information about a block of unused objects and print it to the console. 然后收集未使用的对象,并显示结果的内存总量。The unused objects are then collected, and the resulting memory totals are displayed.

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

注解

垃圾回收器是公共语言运行时组件,用于控制分配和释放的托管内存。The garbage collector is a common language runtime component that controls the allocation and release of managed memory. 对某个对象并释放由对象分配的资源执行垃圾回收时,会影响此类中的方法。The methods in this class influence when garbage collection is performed on an object and when resources allocated by an object are released. 此类中的属性系统和年龄类别或生成,分配给对象的内存中提供信息的总可用内存量。Properties in this class provide information about the total amount of memory available in the system and the age category, or generation, of memory allocated to an object.

垃圾回收器跟踪并回收托管内存中分配的对象。The garbage collector tracks and reclaims objects allocated in managed memory. 我们会定期垃圾回收器执行垃圾回收来回收内存分配给对象没有有效的引用。Periodically, the garbage collector performs garbage collection to reclaim memory allocated to objects for which there are no valid references. 不能满足内存要求,使用可用的可用内存时自动发生垃圾回收。Garbage collection happens automatically when a request for memory cannot be satisfied using available free memory. 或者,应用程序可以强制垃圾收集使用Collect方法。Alternatively, an application can force garbage collection using the Collect method.

垃圾回收包括以下步骤:Garbage collection consists of the following steps:

  1. 垃圾回收器将搜索在托管代码中引用的托管对象。The garbage collector searches for managed objects that are referenced in managed code.

  2. 垃圾回收器尝试完成未引用的对象。The garbage collector tries to finalize objects that are not referenced.

  3. 垃圾回收器释放未引用的对象并回收其内存。The garbage collector frees objects that are not referenced and reclaims their memory.

本主题包括以下部分:This topic includes the following sections:

垃圾回收器和非托管的资源 The garbage collector and unmanaged resources
对象老化和生成 Object aging and generations
不允许垃圾回收Disallowing garbage collection

垃圾回收器和非托管的资源The garbage collector and unmanaged resources

在回收中,垃圾回收器将不会释放对象如果在托管代码中找到该对象的一个或多个引用。During a collection, the garbage collector will not free an object if it finds one or more references to the object in managed code. 但是,垃圾回收器不能识别从非托管代码引用的对象,并且可能会释放正在使用非托管代码中以独占方式除非明确禁止执行此操作的对象。However, the garbage collector does not recognize references to an object from unmanaged code, and might free objects that are being used exclusively in unmanaged code unless explicitly prevented from doing so. KeepAlive方法提供了一种机制,可防止垃圾回收器收集非托管代码中仍在使用的对象。The KeepAlive method provides a mechanism that prevents the garbage collector from collecting objects that are still in use in unmanaged code.

除了托管的内存分配,垃圾回收器的实现不维护有关资源持有的对象,如文件句柄或数据库连接的信息。Aside from managed memory allocations, implementations of the garbage collector do not maintain information about resources held by an object, such as file handles or database connections. 当类型使用该类型的实例将被回收之前,必须释放的非托管的资源时,该类型可以实现终结器。When a type uses unmanaged resources that must be released before instances of the type are reclaimed, the type can implement a finalizer.

在大多数情况下,终结器实现通过重写Object.Finalize方法; 但是,在编写的类型C#或C++实现析构函数,哪些编译器将转换为的重写Object.FinalizeIn most cases, finalizers are implemented by overriding the Object.Finalize method; however, types written in C# or C++ implement destructors, which compilers turn into an override of Object.Finalize. 在大多数情况下,如果对象具有一个终结器,垃圾回收器会调用它之前释放对象。In most cases, if an object has a finalizer, the garbage collector calls it prior to freeing the object. 但是,垃圾回收器不需要在所有情况下; 调用终结器例如,SuppressFinalize方法显式会被调用对象的终结器。However, the garbage collector is not required to call finalizers in all situations; for example, the SuppressFinalize method explicitly prevents an object's finalizer from being called. 此外,垃圾回收器不需要使用特定的线程来完成对象,或保证的相互引用,但适用于垃圾回收的对象调用终结器的顺序。Also, the garbage collector is not required to use a specific thread to finalize objects, or guarantee the order in which finalizers are called for objects that reference each other but are otherwise available for garbage collection.

在其中必须在特定时间释放资源的情况下,类可以实现IDisposable接口,其中包含IDisposable.Dispose执行资源管理和清理任务的方法。In scenarios where resources must be released at a specific time, classes can implement the IDisposable interface, which contains the IDisposable.Dispose method that performs resource management and cleanup tasks. 类实现Dispose必须指定,作为它们的类协定中,如果类使用者调用方法来清理对象。Classes that implement Dispose must specify, as part of their class contract, if and when class consumers call the method to clean up the object. 垃圾回收器不会默认情况下,调用Dispose方法; 但是,实现Dispose方法调用中方法GC类自定义的垃圾回收器终止行为。The garbage collector does not, by default, call the Dispose method; however, implementations of the Dispose method can call methods in the GC class to customize the finalization behavior of the garbage collector.

有关准备对象终止和 dispose 模式的详细信息,请参阅清理了非托管资源For more information on object finalization and the dispose pattern, see Cleaning Up Unmanaged Resources.

对象老化和生成Object aging and generations

公共语言运行时中的垃圾收集器支持使用代对象老化。The garbage collector in the common language runtime supports object aging using generations. 生成是内存中对象的相对存在时间度量单位。A generation is a unit of measure of the relative age of objects in memory. 生成编号和年龄,对象的表示对象所属的代。The generation number, or age, of an object indicates the generation to which an object belongs. 创建多个对象最近是的较新的生成,并具有较低的生成数字不是对象前面部分创建应用程序生命周期。Objects created more recently are part of newer generations, and have lower generation numbers than objects created earlier in the application life cycle. 第 0 代中是最新代中的对象。Objects in the most recent generation are in generation 0. 垃圾回收器的此实现支持三代的对象、 0、 1 和 2 代。This implementation of the garbage collector supports three generations of objects, generations 0, 1, and 2. 可以检索的值MaxGeneration属性来确定系统支持的最大代数。You can retrieve the value of the MaxGeneration property to determine the maximum generation number supported by the system.

对象老化允许在一组特定的生成,而无需计算所有代垃圾回收器回收应用程序。Object aging allows applications to target garbage collection at a specific set of generations rather than requiring the garbage collector to evaluate all generations. 重载Collect方法,包括generation参数可用于指定最后一代进行垃圾回收。Overloads of the Collect method that include a generation parameter allow you to specify the oldest generation to be garbage collected.

不允许垃圾回收Disallowing garbage collection

从开始.NET Framework 4.6.NET Framework 4.6,垃圾回收器支持无 GC 区域延迟模式,可以在垃圾收集会影响应用程序的性能的关键路径执行期间使用。Starting with the .NET Framework 4.6.NET Framework 4.6, the garbage collector supports a no GC region latency mode that can be used during the execution of critical paths in which garbage collection can adversely affect an app's performance. 无 GC 区域延迟模式要求您指定的可以不受干扰地从垃圾回收器分配的内存量。The no GC region latency mode requires that you specify an amount of memory that can be allocated without interference from the garbage collector. 如果在运行时可以分配内存,运行时代码中的关键路径执行时将执行垃圾回收。If the runtime can allocate that memory, the runtime will not perform a garbage collection while code in the critical path is executing.

通过调用的重载之一定义的无 GC 区域的关键路径开头TryStartNoGCRegionYou define the beginning of the critical path of the no GC region by calling one of the overloads of the TryStartNoGCRegion. 通过调用指定其关键路径的末尾EndNoGCRegion方法。You specify the end of its critical path by calling the EndNoGCRegion method.

不能嵌套调用TryStartNoGCRegion方法,并且你应只调用EndNoGCRegion方法如果运行时当前处于无 GC 区域延迟模式。You cannot nest calls to the TryStartNoGCRegion method, and you should only call the EndNoGCRegion method if the runtime is currently in no GC region latency mode. 换而言之,不应调用TryStartNoGCRegion多个时间 (在第一个方法调用后,后续调用将不会成功),并且不应期望调用EndNoGCRegion成功只是因为第一次调用到TryStartNoGCRegion成功。In other words, you should not call TryStartNoGCRegion multiple times (after the first method call, subsequent calls will not succeed), and you should not expect calls to EndNoGCRegion to succeed just because the first call to TryStartNoGCRegion succeeded.

属性

MaxGeneration MaxGeneration MaxGeneration MaxGeneration

获取系统当前支持的最大代数。Gets the maximum number of generations that the system currently supports.

方法

AddMemoryPressure(Int64) AddMemoryPressure(Int64) AddMemoryPressure(Int64) AddMemoryPressure(Int64)

通知运行时在安排垃圾回收时应考虑分配大量的非托管内存。Informs the runtime of a large allocation of unmanaged memory that should be taken into account when scheduling garbage collection.

CancelFullGCNotification() CancelFullGCNotification() CancelFullGCNotification() CancelFullGCNotification()

取消注册垃圾回收通知。Cancels the registration of a garbage collection notification.

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.

CollectionCount(Int32) CollectionCount(Int32) CollectionCount(Int32) CollectionCount(Int32)

返回已经对对象的指定代进行的垃圾回收次数。Returns the number of times garbage collection has occurred for the specified generation of objects.

EndNoGCRegion() EndNoGCRegion() EndNoGCRegion() EndNoGCRegion()

结束无 GC 区域延迟模式。Ends the no GC region latency mode.

GetAllocatedBytesForCurrentThread() GetAllocatedBytesForCurrentThread() GetAllocatedBytesForCurrentThread() GetAllocatedBytesForCurrentThread()

获取自当前线程的生存期开始以来分配给它的总字节数。Gets the total number of bytes allocated to the current thread since the beginning of its lifetime.

GetGeneration(Object) GetGeneration(Object) GetGeneration(Object) GetGeneration(Object)

返回指定对象的当前代数。Returns the current generation number of the specified object.

GetGeneration(WeakReference) GetGeneration(WeakReference) GetGeneration(WeakReference) GetGeneration(WeakReference)

返回指定弱引用的目标的当前代数。Returns the current generation number of the target of a specified weak reference.

GetTotalMemory(Boolean) GetTotalMemory(Boolean) GetTotalMemory(Boolean) GetTotalMemory(Boolean)

检索当前认为要分配的字节数。Retrieves the number of bytes currently thought to be allocated. 一个参数,指示此方法是否可以等待较短间隔再返回,以便系统回收垃圾和终结对象。A parameter indicates whether this method can wait a short interval before returning, to allow the system to collect garbage and finalize objects.

KeepAlive(Object) KeepAlive(Object) KeepAlive(Object) KeepAlive(Object)

引用指定对象,使其从当前例程开始到调用此方法的那一刻为止均不符合进行垃圾回收的条件。References the specified object, which makes it ineligible for garbage collection from the start of the current routine to the point where this method is called.

RegisterForFullGCNotification(Int32, Int32) RegisterForFullGCNotification(Int32, Int32) RegisterForFullGCNotification(Int32, Int32) RegisterForFullGCNotification(Int32, Int32)

指定当条件支持完整垃圾回收以及回收完成时,应引发垃圾回收通知。Specifies that a garbage collection notification should be raised when conditions favor full garbage collection and when the collection has been completed.

RemoveMemoryPressure(Int64) RemoveMemoryPressure(Int64) RemoveMemoryPressure(Int64) RemoveMemoryPressure(Int64)

通知运行时已释放非托管内存,在安排垃圾回收时不需要再考虑它。Informs the runtime that unmanaged memory has been released and no longer needs to be taken into account when scheduling garbage collection.

ReRegisterForFinalize(Object) ReRegisterForFinalize(Object) ReRegisterForFinalize(Object) ReRegisterForFinalize(Object)

请求系统调用指定对象的终结器,此前已为该对象调用 SuppressFinalize(Object)Requests that the system call the finalizer for the specified object for which SuppressFinalize(Object) has previously been called.

SuppressFinalize(Object) SuppressFinalize(Object) SuppressFinalize(Object) SuppressFinalize(Object)

请求公共语言运行时不要调用指定对象的终结器。Requests that the common language runtime not call the finalizer for the specified object.

TryStartNoGCRegion(Int64) TryStartNoGCRegion(Int64) TryStartNoGCRegion(Int64) TryStartNoGCRegion(Int64)

如果指定数量的内存可用,则在关键路径执行期间尝试禁止垃圾回收。Attempts to disallow garbage collection during the execution of a critical path if a specified amount of memory is available.

TryStartNoGCRegion(Int64, Boolean) TryStartNoGCRegion(Int64, Boolean) TryStartNoGCRegion(Int64, Boolean) TryStartNoGCRegion(Int64, Boolean)

如果指定数量的内存可用,则在关键路径执行期间尝试禁止垃圾回收;并在初始没有足够内存可用的情况下,控制垃圾回收器是否进行完整的阻碍性垃圾回收。Attempts to disallow garbage collection during the execution of a critical path if a specified amount of memory is available, and controls whether the garbage collector does a full blocking garbage collection if not enough memory is initially available.

TryStartNoGCRegion(Int64, Int64) TryStartNoGCRegion(Int64, Int64) TryStartNoGCRegion(Int64, Int64) TryStartNoGCRegion(Int64, Int64)

如果指定数量的内存可用于大对象堆和小对象堆,则在关键路径执行期间尝试禁止垃圾回收。Attempts to disallow garbage collection during the execution of a critical path if a specified amount of memory is available for the large object heap and the small object heap.

TryStartNoGCRegion(Int64, Int64, Boolean) TryStartNoGCRegion(Int64, Int64, Boolean) TryStartNoGCRegion(Int64, Int64, Boolean) TryStartNoGCRegion(Int64, Int64, Boolean)

如果指定数量的内存可用大对象堆和小对象堆,则在关键路径执行期间尝试禁止垃圾回收;并在初始没有足够内存可用的情况下,控制垃圾回收器是否进行完整的阻碍性垃圾回收。Attempts to disallow garbage collection during the execution of a critical path if a specified amount of memory is available for the large object heap and the small object heap, and controls whether the garbage collector does a full blocking garbage collection if not enough memory is initially available.

WaitForFullGCApproach() WaitForFullGCApproach() WaitForFullGCApproach() WaitForFullGCApproach()

返回已注册通知的状态,用于确定公共语言运行时是否即将引发完整、阻碍性垃圾回收。Returns the status of a registered notification for determining whether a full, blocking garbage collection by the common language runtime is imminent.

WaitForFullGCApproach(Int32) WaitForFullGCApproach(Int32) WaitForFullGCApproach(Int32) WaitForFullGCApproach(Int32)

在指定的超时期限内,返回已注册通知的状态,用于确定公共语言运行时是否即将引发完整、阻碍性垃圾回收。Returns, in a specified time-out period, the status of a registered notification for determining whether a full, blocking garbage collection by the common language runtime is imminent.

WaitForFullGCComplete() WaitForFullGCComplete() WaitForFullGCComplete() WaitForFullGCComplete()

返回已注册通知的状态,用于确定公共语言运行时引发的完整、阻碍性垃圾回收是否已完成。Returns the status of a registered notification for determining whether a full, blocking garbage collection by the common language runtime has completed.

WaitForFullGCComplete(Int32) WaitForFullGCComplete(Int32) WaitForFullGCComplete(Int32) WaitForFullGCComplete(Int32)

在指定的超时期限内,返回已注册通知的状态,用于确定公共语言运行时引发的完整、阻碍性垃圾回收是否已完成。Returns, in a specified time-out period, the status of a registered notification for determining whether a full, blocking garbage collection by common language the runtime has completed.

WaitForPendingFinalizers() WaitForPendingFinalizers() WaitForPendingFinalizers() WaitForPendingFinalizers()

挂起当前线程,直到处理终结器队列的线程清空该队列为止。Suspends the current thread until the thread that is processing the queue of finalizers has emptied that queue.

适用于

另请参阅