語言

GC.Collect 方法

定義

強制垃圾回收。

多載

名稱 Description
Collect()

強制立即進行各代垃圾回收。

Collect(Int32)

強制從第 0 代到指定世代立即進行垃圾回收。

Collect(Int32, GCCollectionMode)

強制從第 0 代到指定世代,並在由值 GCCollectionMode 指定的時間內進行垃圾回收。

Collect(Int32, GCCollectionMode, Boolean)

強制垃圾回收從第 0 代到指定世代,並在由一個 GCCollectionMode 值指定的時間點執行,該值指定該集合是否應該阻塞。

Collect(Int32, GCCollectionMode, Boolean, Boolean)

強制垃圾回收從第 0 代到指定世代,時間由一個 GCCollectionMode 值指定,該值指定集合是否應阻塞與壓縮。

Collect()

來源:
GC.CoreCLR.cs
來源:
GC.CoreCLR.cs
來源:
GC.CoreCLR.cs
來源:
GC.CoreCLR.cs
來源:
GC.CoreCLR.cs

強制立即進行各代垃圾回收。

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

範例

以下範例示範如何使用此 Collect 方法對所有世代的記憶進行收集。 程式碼會產生多個未使用的物件,然後呼叫 Collect 該方法將它們從記憶體中清除。

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

備註

用這個方法嘗試回收所有無法存取的記憶體。 它執行所有世代的阻塞垃圾回收。

所有物件,不論在記憶體中存在多久,都被視為收集對象;然而,在受管理程式碼中被引用的物件則不會被收集。 使用此方法強制系統嘗試回收最大可用記憶體。

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

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

另請參閱

適用於

Collect(Int32)

來源:
GC.CoreCLR.cs
來源:
GC.CoreCLR.cs
來源:
GC.CoreCLR.cs
來源:
GC.CoreCLR.cs
來源:
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 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)

來源:
GC.CoreCLR.cs
來源:
GC.CoreCLR.cs
來源:
GC.CoreCLR.cs
來源:
GC.CoreCLR.cs
來源:
GC.CoreCLR.cs

強制從第 0 代到指定世代,並在由值 GCCollectionMode 指定的時間內進行垃圾回收。

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

一個列舉值,指定垃圾回收是強制Default (或 Forced)還是優化(Optimized)。

例外狀況

generation 不成立。

-或-

mode 不是其中 GCCollectionMode 的價值觀之一。

範例

以下範例強制對第2世代物件進行垃圾回收,並設定 Optimized 該設定。

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)

來源:
GC.CoreCLR.cs
來源:
GC.CoreCLR.cs
來源:
GC.CoreCLR.cs
來源:
GC.CoreCLR.cs
來源:
GC.CoreCLR.cs

強制垃圾回收從第 0 代到指定世代,並在由一個 GCCollectionMode 值指定的時間點執行,該值指定該集合是否應該阻塞。

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

一個列舉值,指定垃圾回收是強制Default (或 Forced)還是優化(Optimized)。

blocking
Boolean

true 執行阻塞性垃圾回收; false 盡可能執行背景垃圾回收。

例外狀況

generation 不成立。

-或-

mode 不是其中 GCCollectionMode 的價值觀之一。

備註

下表總結了 和 mode 參數的blocking交互作用:

mode blocking 是 true blocking 是 false
Forced 或 Default 會儘快執行封鎖集合。 如果背景收集正在進行中且 generation 為 0 或 1,該 Collect(Int32, GCCollectionMode, Boolean) 方法會立即觸發區塊收集,並在收集結束後返回。 如果背景集合正在進行中且 generation 是 2,方法會等到背景集合完成後,觸發阻塞的第二世代集合,然後返回。 收集將盡快進行。 Collect(Int32, GCCollectionMode, Boolean)方法會要求背景集合,但這並不保證;視情況而定,仍可能會執行封鎖集合。 如果背景收集程序正在進行中,方法會立即返回。
Optimized 根據垃圾收集器的狀態和 generation 參數,可能會執行阻塞集合。 垃圾收集器會嘗試提供最佳效能。 根據垃圾收集器的狀態,可能會執行收集動作。 Collect(Int32, GCCollectionMode, Boolean)方法會要求背景集合,但這並不保證;視情況而定,仍可能會執行封鎖集合。 垃圾收集器會嘗試提供最佳效能。 如果背景收集程序正在進行中,方法會立即返回。

如果呼叫該Collect(Int32, GCCollectionMode, Boolean)方法執行完整的阻塞垃圾回收,你也可以在呼叫GCSettings.LargeObjectHeapCompactionMode方法前將 屬性設GCLargeObjectHeapCompactionMode.CompactOnce為 來Collect壓縮大型物件堆積。

適用於

Collect(Int32, GCCollectionMode, Boolean, Boolean)

來源:
GC.CoreCLR.cs
來源:
GC.CoreCLR.cs
來源:
GC.CoreCLR.cs
來源:
GC.CoreCLR.cs
來源:
GC.CoreCLR.cs

強制垃圾回收從第 0 代到指定世代,時間由一個 GCCollectionMode 值指定,該值指定集合是否應阻塞與壓縮。

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

一個列舉值,指定垃圾回收是強制Default (或 Forced)還是優化(Optimized)。

blocking
Boolean

true 執行阻塞性垃圾回收; false 盡可能執行背景垃圾回收。

compacting
Boolean

true 壓縮小型物件堆; false 只是用來掃。

備註

若 blocking , falseGC 決定執行背景或阻塞垃圾回收。 若 compacting 為 , true則執行阻塞垃圾回收。

若 compacting 為 , true執行時會壓縮小物件堆(SOH)。 除非 GCSettings.LargeObjectHeapCompactionMode 將屬性設定為 GCLargeObjectHeapCompactionMode.CompactOnce,否則大型物件堆(LOH)不會被壓縮。 請注意,這包括所有阻擋垃圾回收,而不只是完整的阻擋垃圾回收。

你可以呼叫 Collect(Int32, GCCollectionMode, Boolean, Boolean) 將受管理堆縮減到最小大小的方法,如下方程式碼片段所示。

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)

為參數指定truecompacting即可保證一個壓縮且完整的阻塞垃圾回收。 將屬性設定 GCSettings.LargeObjectHeapCompactionMode 為 可以 GCLargeObjectHeapCompactionMode.CompactOnce 確保 LOH 和 SOH 都被壓縮。

適用於