GC.Collect メソッド

定義

強制的にガベージ コレクションを行います。

オーバーロード

Collect()

すべてのジェネレーションのガベージ コレクションを直ちに強制実行します。

Collect(Int32)

ジェネレーション 0 から指定ジェネレーションまでのガベージ コレクションを直ちに強制実行します。

Collect(Int32, GCCollectionMode)

GCCollectionMode 値によって指定したタイミングで、ジェネレーション 0 から指定ジェネレーションまでのガベージ コレクションを強制的に実行します。

Collect(Int32, GCCollectionMode, Boolean)

ジェネレーション 0 から指定ジェネレーションまでのガベージ コレクションを、 GCCollectionMode 値で指定したタイミングで強制実行します。コレクションをブロックする必要があるかどうかを指定する値を指定します。

Collect(Int32, GCCollectionMode, Boolean, Boolean)

ジェネレーション 0 から指定ジェネレーションまでのガベージ コレクションを、 GCCollectionMode 値で指定したタイミングで強制実行します。コレクションをブロックおよび圧縮する必要があるかどうかを指定する値を指定します。

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

注釈

アクセスできないすべてのメモリを再利用するには、このメソッドを使用します。 すべての世代のブロッキング ガベージ コレクションを実行します。

メモリ内にある期間に関係なく、すべてのオブジェクトはコレクションと見なされます。ただし、マネージド コードで参照されているオブジェクトは収集されません。 このメソッドを使用して、システムで使用可能なメモリの最大量を強制的に回収します。

次の例に示すように、.NET Framework 4.5.1 以降では、メソッドを呼び出すCollect前に プロパティを GCSettings.LargeObjectHeapCompactionModeGCLargeObjectHeapCompactionMode.CompactOnce設定することで、ラージ オブジェクト ヒープ (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

ガベージ コレクションが強制実行になっている (Default または Forced) か、最適化になっている (Optimized) かを示す列挙値。

例外

generation が無効です。

または

modeGCCollectionMode 値のいずれでもありません。

次の例では、 設定を使用してジェネレーション 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)

Source:
GC.CoreCLR.cs
Source:
GC.CoreCLR.cs
Source:
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 が無効です。

または

modeGCCollectionMode 値のいずれでもありません。

注釈

次の表は、 パラメーターと blocking パラメーターの相互作用をmodeまとめたものです。

mode blockingtrue です blockingfalse です
Forced または Default ブロッキング コレクションはできるだけ早く実行されます。 バックグラウンド コレクションが進行中 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

ジェネレーション 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

注釈

が のfalse場合blocking、GC はバックグラウンドまたはブロッキング ガベージ コレクションのどちらを実行するかを決定します。 が の場合 compactingtrueブロッキング ガベージ コレクションが実行されます。

trueの場合compacting、ランタイムは小さなオブジェクト ヒープ (SOH) を最適化します。 プロパティが にGCLargeObjectHeapCompactionMode.CompactOnce設定されていない限りGCSettings.LargeObjectHeapCompactionMode、ラージ オブジェクト ヒープ (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)

引数に compacting を指定するとtrue、完全にブロックされるガベージ コレクションの圧縮が保証されます。 プロパティを GCSettings.LargeObjectHeapCompactionModeGCLargeObjectHeapCompactionMode.CompactOnce 設定すると、LOH と SOH の両方が圧縮されます。

適用対象