GC 類別

定義

控制系統記憶體回收行程,它是自動回收未使用之記憶體的服務。Controls the system garbage collector, a service that automatically reclaims unused memory.

public ref class GC abstract sealed
public ref class GC sealed
public static class GC
public sealed class GC
type GC = class
Public Class GC
Public NotInheritable 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.

垃圾收集行程會追蹤和回收在 managed 記憶體中配置的物件。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. 或者,應用程式可以使用方法強制進行垃圾收集 CollectAlternatively, an application can force garbage collection using the Collect method.

垃圾收集是由下列步驟所組成:Garbage collection consists of the following steps:

  1. 垃圾收集行程會搜尋 managed 程式碼中所參考的 managed 物件。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

在集合期間,如果在 managed 程式碼中找到物件的一或多個參考,垃圾收集行程就不會釋放物件。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.

除了 managed 記憶體配置,垃圾收集行程的執行不會維護物件所持有的資源相關資訊,例如檔案控制代碼或資料庫連接。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.

如需物件結束和處置模式的詳細資訊,請參閱 清除非受控資源For more information on object finalization and the dispose pattern, see Cleaning Up Unmanaged Resources.

物件過時和世代Object aging and generations

Common language runtime 中的垃圾收集行程支援使用層代的物件過時。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. 包含參數之方法的多載,可 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. 您可以藉由呼叫方法來指定其關鍵路徑的結尾 EndNoGCRegionYou 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 只有在第一次呼叫成功時,才會成功的呼叫 TryStartNoGCRegionIn 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)

告知執行階段,在排定記憶體回收時應考慮的大量 Unmanaged 記憶體配置。Informs the runtime of a large allocation of unmanaged memory that should be taken into account when scheduling garbage collection.

AllocateArray<T>(Int32, Boolean)

配置陣列。Allocates an array.

AllocateUninitializedArray<T>(Int32, Boolean)

如果可能的話,會在略過零初始化的情況下配置陣列。Allocates an array while skipping zero-initialization, if possible.

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.

GetGCMemoryInfo(GCKind)

取得記憶體回收的記憶體資訊。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)

告知執行階段,Unmanaged 記憶體已釋放,所以排定記憶體回收時不需要再考慮它。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)

要求 Common Language Runtime 不要為指定之物件呼叫完成項。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()

傳回註冊通知的狀態,以判斷 Common Language Runtime 是否即將執行完整的封鎖記憶體回收。Returns the status of a registered notification for determining whether a full, blocking garbage collection by the common language runtime is imminent.

WaitForFullGCApproach(Int32)

在指定的逾時期間傳回註冊通知的狀態,以判斷 Common Language Runtime 是否即將執行完整的封鎖記憶體回收。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()

傳回註冊通知的狀態,以判斷 Common Language Runtime 是否已完成完整的封鎖記憶體回收。Returns the status of a registered notification for determining whether a full, blocking garbage collection by the common language runtime has completed.

WaitForFullGCComplete(Int32)

在指定的逾時期間傳回註冊通知的狀態,以判斷 Common Language Runtime 是否已完成完整的封鎖記憶體回收。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.

適用於

另請參閱