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.

無論物件在記憶體中的時間長度為何,所有物件都會考慮進行收集;但是,不會收集 managed 程式碼中所參考的物件。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)

強制立即執行層代 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 可以使用屬性來判斷參數的最大有效值 generationUse 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.

範例

下列範例會強制具有設定的層代2物件進行垃圾收集 OptimizedThe 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.

垃圾收集行程不會收集產生編號高於參數所指定的物件 generationThe 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)

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.

備註

下表摘要說明和參數的互動 mode blockingThe 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 CollectIf 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.

備註

如果 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) 方法,將 managed 堆積減少到可能的最小大小,如下列程式碼片段所示。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)

true針對 compacting 引數指定可保證壓縮、完全封鎖的垃圾收集。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.

適用於