Export (0) Print
Expand All

GC.Collect Method

Forces an immediate garbage collection of all generations.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

public static void Collect()

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;

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.
      Console.WriteLine("Memory used before collection:       {0:N0}", 

      // Collect all generations of memory.
      Console.WriteLine("Memory used after full collection:   {0:N0}", 

   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

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

© 2014 Microsoft