GC.Collect メソッド

定義

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

オーバーロード

Collect(Int32, GCCollectionMode, Boolean)

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

Collect(Int32, GCCollectionMode)

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

Collect(Int32, GCCollectionMode, Boolean, Boolean)

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

Collect()

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

Collect(Int32)

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

Collect(Int32, GCCollectionMode, Boolean)

ジェネレーション 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.CompactOnceGCSettings.LargeObjectHeapCompactionMode設定することで、大きなオブジェクト ヒープをCollect圧縮することもできます。

適用対象

Collect(Int32, GCCollectionMode)

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, Boolean)

ジェネレーション 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 、GC は falseバックグラウンドを実行するか、ブロックガベージ コレクションを実行するかを決定します。 その場合 compactingtrue、ブロッキング ガベージ コレクションが実行されます。

そのtrue場合compacting、ランタイムは小さなオブジェクト ヒープ (SOH) を圧縮します。 The large object heap (LOH) is not compacted unless the GCSettings.LargeObjectHeapCompactionMode property is set to GCLargeObjectHeapCompactionMode.CompactOnce. これには、完全にブロックされるガベージ コレクションだけでなく、すべてのブロッキング ガベージ コレクションが含まれます。

次のコード フラグメントが 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.LargeObjectHeapCompactionMode 設定すると GCLargeObjectHeapCompactionMode.CompactOnce 、LOH と SOH の両方が確実に圧縮されます。

適用対象

Collect()

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

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前にプロパティを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)

ジェネレーション 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) 使用します。

こちらもご覧ください

適用対象