GC 类

定义

控制系统垃圾回收器(一种自动回收未使用内存的服务)。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

示例

下面的示例使用几个 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();
            }
        }
    }
}
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. 或者,应用程序可以使用 @no__t 0 方法强制进行垃圾回收。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. @No__t-0 方法提供一种机制,该机制可防止垃圾回收器收集仍在非托管代码中使用的对象。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.Finalize 的重写。In 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 接口,该接口包含执行资源管理和清理任务的 @no__t 1 方法。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 方法的实现可调用 @no__t 2 类中的方法来自定义垃圾回收器的终止行为。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.

有关对象终止和释放模式的详细信息,请参阅清理非托管资源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. 对象的代数或 age 指示对象所属的代。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. 包含 generation 参数的 Collect 方法的重载允许您指定要进行垃圾回收的最早代。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.

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

不能将调用嵌套到 TryStartNoGCRegion 方法,只应在运行时当前处于无 GC 区域延迟模式时调用 EndNoGCRegion 方法。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

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

方法

AddMemoryPressure(Int64)

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

CancelFullGCNotification()

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

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.

CollectionCount(Int32)

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

EndNoGCRegion()

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

GetAllocatedBytesForCurrentThread()

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

GetGCMemoryInfo()

获取垃圾回收的内存信息。Gets garbage collection memory information.

GetGeneration(Object)

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

GetGeneration(WeakReference)

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

GetTotalAllocatedBytes(Boolean)

获取在进程生命周期内分配的字节计数。Gets a count of the bytes allocated over the lifetime of the process.

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)

引用指定对象,使其从当前例程开始到调用此方法的那一刻为止均不符合进行垃圾回收的条件。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)

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

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)

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

SuppressFinalize(Object)

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

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)

如果指定数量的内存可用,则在关键路径执行期间尝试禁止垃圾回收;并在初始没有足够内存可用的情况下,控制垃圾回收器是否进行完整的阻碍性垃圾回收。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)

如果指定数量的内存可用于大对象堆和小对象堆,则在关键路径执行期间尝试禁止垃圾回收。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)

如果指定数量的内存可用大对象堆和小对象堆,则在关键路径执行期间尝试禁止垃圾回收;并在初始没有足够内存可用的情况下,控制垃圾回收器是否进行完整的阻碍性垃圾回收。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()

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

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

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

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

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

适用于

另请参阅