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.

所有的物件,不論時間已在記憶體中,會被視為集合;不過,不會收集在 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) 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)方法,以減少大小最小,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.

適用於