GC.Collect Method

Definition

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 ();

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

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();

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

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);

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

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

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

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);

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

generation is not valid.

-or-

mode is not one of the GCCollectionMode values.

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);
    }
}

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

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

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);

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

generation is not valid.

-or-

mode is not one of the GCCollectionMode values.

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

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

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);

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);

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.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1