GC.Collect 方法

定義

強制記憶體回收。

多載

Collect()

強制立即執行所有層代的記憶體回收。

Collect(Int32)

強制立即執行層代 0 至指定層代的記憶體回收。

Collect(Int32, GCCollectionMode)

GCCollectionMode 值所指定的時間,強制執行層代 0 至指定層代的記憶體回收。

Collect(Int32, GCCollectionMode, Boolean)

GCCollectionMode 值 (含有指定是否應該封鎖回收作業的值) 所指定的時間,強制執行從層代 0 到指定之層代的記憶體回收。

Collect(Int32, GCCollectionMode, Boolean, Boolean)

GCCollectionMode 值 (含有指定是否應該封鎖及壓縮回收作業的值) 所指定的時間,強制執行從層代 0 到指定之層代的記憶體回收。

Collect()

Source:
GC.CoreCLR.cs
Source:
GC.CoreCLR.cs
Source:
GC.CoreCLR.cs

強制立即執行所有層代的記憶體回收。

public:
 static void Collect();
public static void Collect ();
static member Collect : unit -> unit
Public Shared Sub Collect ()

範例

下列範例示範如何使用 Collect 方法在所有記憶體層代上執行集合。 程式碼會產生許多未使用的物件,然後呼叫 Collect 方法來從記憶體中清除它們。

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
open System

let maxGarbage = 1000

let makeSomeGarbage () =
    // Create objects and release them to fill up memory with unused objects.
    for _ = 1 to maxGarbage do 
        Version() |> ignore

// Put some objects in memory.
makeSomeGarbage()
printfn $"Memory used before collection:       {GC.GetTotalMemory false:N0}"

// Collect all generations of memory.
GC.Collect()
printfn $"Memory used after full collection:   {GC.GetTotalMemory true:N0}"

// 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

備註

使用此方法嘗試回收無法存取的所有記憶體。 它會執行所有世代的封鎖垃圾收集。

不論物件在記憶體中的時間長度為何,都會被視為收集物件;不過,不會收集 Managed 程式碼中所參考的物件。 使用此方法強制系統嘗試回收可用記憶體數量上限。

從 .NET Framework 4.5.1 開始,您可以藉由在呼叫 Collect 方法之前將 屬性 GCLargeObjectHeapCompactionMode.CompactOnce 設定 GCSettings.LargeObjectHeapCompactionMode 為 ,以壓縮大型物件堆積 (LOH) ,如下列範例所示。

GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect();
GCSettings.LargeObjectHeapCompactionMode <- GCLargeObjectHeapCompactionMode.CompactOnce
GC.Collect()
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce
GC.Collect()

另請參閱

適用於

Collect(Int32)

Source:
GC.CoreCLR.cs
Source:
GC.CoreCLR.cs
Source:
GC.CoreCLR.cs

強制立即執行層代 0 至指定層代的記憶體回收。

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

要進行記憶體回收的最舊層代數目。

例外狀況

generation 無效。

範例

下列範例示範如何使用 Collect 方法,在個別的記憶體層上執行集合。 程式碼會產生許多未使用的物件,然後呼叫 Collect 方法來從記憶體中清除它們。

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();
            }
        }
    }
}
open System

let maxGarbage = 1000

type MyGCCollectClass() =
    member _.MakeSomeGarbage() =
        for _ = 1 to maxGarbage do
            // Create objects and release them to fill up memory with unused objects.
            Version() |> ignore

[<EntryPoint>]
let main _ =
    let myGCCol = MyGCCollectClass()

    // Determine the maximum number of generations the system
    // garbage collector currently supports.
    printfn $"The highest generation is {GC.MaxGeneration}"

    myGCCol.MakeSomeGarbage()

    // Determine which generation myGCCol object is stored in.
    printfn $"Generation: {GC.GetGeneration myGCCol}"

    // Determine the best available approximation of the number
    // of bytes currently allocated in managed memory.
    printfn $"Total Memory: {GC.GetTotalMemory false}"

    // Perform a collection of generation 0 only.
    GC.Collect 0

    // Determine which generation myGCCol object is stored in.
    printfn $"Generation: {GC.GetGeneration myGCCol}"

    printfn $"Total Memory: {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.
    printfn $"Generation: {GC.GetGeneration myGCCol}"
    printfn $"Total Memory: {GC.GetTotalMemory false}"

    0
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

備註

使用此方法嘗試回收無法存取的記憶體。 不過,使用此方法不保證回收指定世代中的所有無法存取記憶體。

如果實作物件過時,垃圾收集行程不會收集產生編號高於指定世代的物件。 如果未實作物件過時,垃圾收集行程會考慮垃圾收集期間的所有物件。

MaxGeneration使用 屬性來判斷參數的最大 generation 有效值。

若要讓垃圾收集行程考慮所有物件,不論其產生為何,請使用這個方法的版本來接受任何參數。 若要讓垃圾收集行程根據 GCCollectionMode 設定回收物件,請使用 GC.Collect(Int32, GCCollectionMode) 方法多載。

另請參閱

適用於

Collect(Int32, GCCollectionMode)

Source:
GC.CoreCLR.cs
Source:
GC.CoreCLR.cs
Source:
GC.CoreCLR.cs

GCCollectionMode 值所指定的時間,強制執行層代 0 至指定層代的記憶體回收。

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

要進行記憶體回收的最舊層代數目。

mode
GCCollectionMode

列舉值,指定是要強制記憶體回收 (DefaultForced) 還是進行最佳化 (Optimized)。

例外狀況

generation 無效。

-或-

mode 不是其中一個 GCCollectionMode 值。

範例

下列範例會強制使用 Optimized 設定為第 2 代物件的垃圾收集。

using System;

class Program
{
    static void Main(string[] args)
    {
        GC.Collect(2, GCCollectionMode.Optimized);
    }
}
open System

GC.Collect(2, GCCollectionMode.Optimized)
Class Program

    Public Shared Sub Main()
        GC.Collect(2, GCCollectionMode.Optimized)
    End Sub
End Class

備註

mode使用 參數來指定垃圾收集是否應該立即發生,或只有在回收物件的時間是最佳時。 使用此方法不保證會回收指定世代中的所有無法存取記憶體。

若要在應用程式的重要期間調整垃圾收集的干擾性,請設定 LatencyMode 屬性。

垃圾收集行程不會收集產生編號高於 參數所 generation 指定的 物件。 MaxGeneration使用 屬性來判斷 的最大有效值 generation

若要讓垃圾收集行程考慮所有物件,不論其產生為何,請使用這個方法的版本來接受任何參數。

若要讓垃圾收集行程回收物件至指定的物件世代,請使用 GC.Collect(Int32) 方法多載。 當您指定最大產生時,會收集所有物件。

另請參閱

適用於

Collect(Int32, GCCollectionMode, Boolean)

Source:
GC.CoreCLR.cs
Source:
GC.CoreCLR.cs
Source:
GC.CoreCLR.cs

GCCollectionMode 值 (含有指定是否應該封鎖回收作業的值) 所指定的時間,強制執行從層代 0 到指定之層代的記憶體回收。

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

要進行記憶體回收的最舊層代數目。

mode
GCCollectionMode

列舉值,指定是要強制記憶體回收 (DefaultForced) 還是進行最佳化 (Optimized)。

blocking
Boolean

true 表示要執行封鎖記憶體回收,false 表示要盡可能執行背景記憶體回收。

例外狀況

generation 無效。

-或-

mode 不是其中一個 GCCollectionMode 值。

備註

下表摘要說明 和 blocking 參數的 mode 互動:

mode blockingtrue blockingfalse
ForcedDefault 會盡快執行封鎖回收。 如果背景集合正在進行且 generation 為 0 或 1, Collect(Int32, GCCollectionMode, Boolean) 此方法會立即觸發封鎖集合,並在集合完成時傳回。 如果背景集合正在進行中且 generation 為 2,則方法會等到背景集合完成,觸發封鎖第 2 代集合,然後傳回 。 會盡快執行回收。 Collect(Int32, GCCollectionMode, Boolean) 方法會要求背景集合,但不保證可取得。視情況而定,可能仍會執行封鎖集合。 如果已在進行背景回收,則這個方法會立即返回。
Optimized 可能會因記憶體回收行程和 generation 參數的狀態而執行封鎖集合。 記憶體回收行程會嘗試提供最佳效能。 根據記憶體回收行程的狀態,可能會執行回收。 Collect(Int32, GCCollectionMode, Boolean) 方法會要求背景集合,但不保證可取得。視情況而定,可能仍會執行封鎖集合。 記憶體回收行程會嘗試提供最佳效能。 如果已在進行背景回收,則這個方法會立即返回。

如果呼叫 Collect(Int32, GCCollectionMode, Boolean) 方法會執行完整的封鎖垃圾收集,您也可以先將 屬性 GCLargeObjectHeapCompactionMode.CompactOnce 設定 GCSettings.LargeObjectHeapCompactionMode 為 以壓縮大型物件堆積,再呼叫 Collect 方法。

適用於

Collect(Int32, GCCollectionMode, Boolean, Boolean)

Source:
GC.CoreCLR.cs
Source:
GC.CoreCLR.cs
Source:
GC.CoreCLR.cs

GCCollectionMode 值 (含有指定是否應該封鎖及壓縮回收作業的值) 所指定的時間,強制執行從層代 0 到指定之層代的記憶體回收。

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

要進行記憶體回收的最舊層代數目。

mode
GCCollectionMode

列舉值,指定是要強制記憶體回收 (DefaultForced) 還是進行最佳化 (Optimized)。

blocking
Boolean

true 表示要執行封鎖記憶體回收,false 表示要盡可能執行背景記憶體回收。

compacting
Boolean

true 表示壓縮小型物件堆積;false 表示僅整理。

備註

如果 為 blockingfalse ,GC 會決定是否要執行背景或封鎖垃圾收集。 如果 為 compactingtrue ,則會執行封鎖垃圾收集。

如果 compactingtrue ,執行時間會壓縮小型物件堆積, (SOH) 。 除非 GCSettings.LargeObjectHeapCompactionMode 屬性設定 GCLargeObjectHeapCompactionMode.CompactOnce 為 ,否則不會壓縮大型物件堆積 (LOH) 。 請注意,這包括所有封鎖垃圾收集,而不只是完整封鎖垃圾收集。

您可以呼叫 Collect(Int32, GCCollectionMode, Boolean, Boolean) 方法,以盡可能將 Managed 堆積縮減為最小大小,如下列程式碼片段所示。

GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect(2, GCCollectionMode.Forced, true, true);
GCSettings.LargeObjectHeapCompactionMode <- GCLargeObjectHeapCompactionMode.CompactOnce
GC.Collect(2, GCCollectionMode.Forced, true, true)
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce
GC.Collect(2, GCCollectionMode.Forced, True, True)

true指定 自 compacting 變數可保證壓縮、完整封鎖垃圾收集。 GCSettings.LargeObjectHeapCompactionMode設定 屬性以確保 GCLargeObjectHeapCompactionMode.CompactOnce 已壓縮 LOH 和 SOH。

適用於