GC.Collect Method
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Forces garbage collection.
Overloads
Collect() |
Forces an immediate garbage collection of all generations. |
Collect(Int32) |
Forces an immediate garbage collection from generation 0 through a specified generation. |
Collect(Int32, GCCollectionMode) |
Forces a garbage collection from generation 0 through a specified generation, at a time specified by a GCCollectionMode value. |
Collect(Int32, GCCollectionMode, Boolean) |
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) |
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()
- Source:
- GC.CoreCLR.cs
- Source:
- GC.CoreCLR.cs
- Source:
- GC.CoreCLR.cs
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 ()
Examples
The following example demonstrates how to use the Collect method to perform a collection on all generations of memory. 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
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
Remarks
Use this method to try to reclaim all memory that is inaccessible. It performs a blocking garbage collection of all generations.
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.
Starting with the .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()
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce
GC.Collect()
See also
Applies to
Collect(Int32)
- Source:
- GC.CoreCLR.cs
- Source:
- GC.CoreCLR.cs
- Source:
- GC.CoreCLR.cs
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)
Parameters
- generation
- Int32
The number of the oldest generation to be garbage collected.
Exceptions
generation
is not valid.
Examples
The following example demonstrates how to use the Collect method to perform a collection on individual layers of memory. 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();
}
}
}
}
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
Remarks
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.
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. To have the garbage collector reclaim objects based on a GCCollectionMode setting, use the GC.Collect(Int32, GCCollectionMode) method overload.
See also
Applies to
Collect(Int32, GCCollectionMode)
- Source:
- GC.CoreCLR.cs
- Source:
- GC.CoreCLR.cs
- Source:
- GC.CoreCLR.cs
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)
Parameters
- generation
- Int32
The number of the oldest generation to be garbage collected.
- mode
- GCCollectionMode
An enumeration value that specifies whether the garbage collection is forced (Default or Forced) or optimized (Optimized).
Exceptions
Examples
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);
}
}
open System
GC.Collect(2, GCCollectionMode.Optimized)
Class Program
Public Shared Sub Main()
GC.Collect(2, GCCollectionMode.Optimized)
End Sub
End Class
Remarks
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.
To adjust the intrusiveness of garbage collection during critical periods in your application, set the LatencyMode property.
The garbage collector does not collect objects with a generation number higher than specified by the generation
parameter. Use 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.
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.
See also
Applies to
Collect(Int32, GCCollectionMode, Boolean)
- Source:
- GC.CoreCLR.cs
- Source:
- GC.CoreCLR.cs
- Source:
- GC.CoreCLR.cs
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)
Parameters
- generation
- Int32
The number of the oldest generation to be garbage collected.
- mode
- GCCollectionMode
An enumeration value that specifies whether the garbage collection is forced (Default or Forced) or optimized (Optimized).
- blocking
- Boolean
true
to perform a blocking garbage collection; false
to perform a background garbage collection where possible.
Exceptions
Remarks
The following table summarizes the interaction of the mode
and blocking
parameters:
mode |
blocking is true |
blocking is false |
---|---|---|
Forced or Default | A blocking collection is performed as soon as possible. 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. 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. 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 | 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. 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. |
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.
Applies to
Collect(Int32, GCCollectionMode, Boolean, Boolean)
- Source:
- GC.CoreCLR.cs
- Source:
- GC.CoreCLR.cs
- Source:
- GC.CoreCLR.cs
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)
Parameters
- generation
- Int32
The number of the oldest generation to be garbage collected.
- mode
- GCCollectionMode
An enumeration value that specifies whether the garbage collection is forced (Default or Forced) or optimized (Optimized).
- blocking
- Boolean
true
to perform a blocking garbage collection; false
to perform a background garbage collection where possible.
- compacting
- Boolean
true
to compact the small object heap; false
to sweep only.
Remarks
If blocking
is false
, the GC decides whether to perform a background or a blocking garbage collection. If compacting
is true
, it performs a blocking garbage collection.
If compacting
is true
, the runtime compacts the small object heap (SOH). The 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.
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)
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce
GC.Collect(2, GCCollectionMode.Forced, True, True)
Specifying true
for the compacting
argument guarantees a compacting, full blocking garbage collection. Setting the GCSettings.LargeObjectHeapCompactionMode property to GCLargeObjectHeapCompactionMode.CompactOnce ensures that both the LOH and SOH are compacted.