Windows Dev Center

Collapse the table of content
Expand the table of content
Expand Minimize
Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

GC Class

Controls the system garbage collector, a service that automatically reclaims unused memory.

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

public static class GC

The GC type exposes the following members.

  NameDescription
Public propertyStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryMaxGenerationGets the maximum number of generations that the system currently supports.
Top

  NameDescription
Public methodStatic memberSupported by Portable Class LibraryAddMemoryPressureInforms the runtime of a large allocation of unmanaged memory that should be taken into account when scheduling garbage collection.
Public methodStatic memberCancelFullGCNotificationCancels the registration of a garbage collection notification.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryCollect()Forces an immediate garbage collection of all generations.
Public methodStatic memberSupported by Portable Class LibraryCollect(Int32)Forces an immediate garbage collection from generation 0 through a specified generation.
Public methodStatic memberSupported by Portable Class LibraryCollect(Int32, GCCollectionMode)Forces a garbage collection from generation 0 through a specified generation, at a time specified by a GCCollectionMode value.
Public methodStatic memberCollect(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.
Public methodStatic memberCollect(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.
Public methodStatic memberSupported by Portable Class LibraryCollectionCountReturns the number of times garbage collection has occurred for the specified generation of objects.
Public methodStatic memberEndNoGCRegionEnds the no GC region latency mode.
Public methodStatic memberGetGeneration(Object)Returns the current generation number of the specified object.
Public methodStatic memberGetGeneration(WeakReference)Returns the current generation number of the target of a specified weak reference.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryGetTotalMemoryRetrieves the number of bytes currently thought to be allocated. A parameter indicates whether this method can wait a short interval before returning, to allow the system to collect garbage and finalize objects.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryKeepAliveReferences the specified object, which makes it ineligible for garbage collection from the start of the current routine to the point where this method is called.
Public methodStatic memberRegisterForFullGCNotificationSpecifies that a garbage collection notification should be raised when conditions favor full garbage collection and when the collection has been completed.
Public methodStatic memberSupported by Portable Class LibraryRemoveMemoryPressureInforms the runtime that unmanaged memory has been released and no longer needs to be taken into account when scheduling garbage collection.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryReRegisterForFinalizeRequests that the system call the finalizer for the specified object for which SuppressFinalize has previously been called.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySuppressFinalizeRequests that the common language runtime not call the finalizer for the specified object.
Public methodStatic memberTryStartNoGCRegion(Int64)Attempts to disallow garbage collection during the execution of a critical path if a specified amount of memory is available.
Public methodStatic memberTryStartNoGCRegion(Int64, Boolean)Attempts to disallow garbage collection during the execution of a critical path if a specified amount of memory is available, and controls whether the garbage collector does a full blocking garbage collection if not enough memory is initially available.
Public methodStatic memberTryStartNoGCRegion(Int64, Int64)Attempts to disallow garbage collection during the execution of a critical path if a specified amount of memory is available for the large object heap and the small object heap.
Public methodStatic memberTryStartNoGCRegion(Int64, Int64, Boolean)Attempts to disallow garbage collection during the execution of a critical path if a specified amount of memory is available for the large object heap and the small object heap, and controls whether the garbage collector does a full blocking garbage collection if not enough memory is initially available.
Public methodStatic memberWaitForFullGCApproach()Returns the status of a registered notification for determining whether a full, blocking garbage collection by the common language runtime is imminent.
Public methodStatic memberWaitForFullGCApproach(Int32)Returns, in a specified time-out period, the status of a registered notification for determining whether a full, blocking garbage collection by the common language runtime is imminent.
Public methodStatic memberWaitForFullGCComplete()Returns the status of a registered notification for determining whether a full, blocking garbage collection by the common language runtime has completed.
Public methodStatic memberWaitForFullGCComplete(Int32)Returns, in a specified time-out period, the status of a registered notification for determining whether a full, blocking garbage collection by common language the runtime has completed.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryWaitForPendingFinalizersSuspends the current thread until the thread that is processing the queue of finalizers has emptied that queue.
Top

The garbage collector is a common language runtime component that controls the allocation and release of managed memory. The methods in this class influence when garbage collection is performed on an object and when resources allocated by an object are released. Properties in this class provide information about the total amount of memory available in the system and the age category, or generation, of memory allocated to an object.

The garbage collector tracks and reclaims objects allocated in managed memory. Periodically, the garbage collector performs garbage collection to reclaim memory allocated to objects for which there are no valid references. Garbage collection happens automatically when a request for memory cannot be satisfied using available free memory. Alternatively, an application can force garbage collection using the Collect method.

Garbage collection consists of the following steps:

  1. The garbage collector searches for managed objects that are referenced in managed code.

  2. The garbage collector tries to finalize objects that are not referenced.

  3. The garbage collector frees objects that are not referenced and reclaims their memory.

This topic includes the following sections:

The garbage collector and unmanaged resources
Object aging and generations
Disallowing garbage collection

The garbage collector and unmanaged resources

During a collection, the garbage collector will not free an object if it finds one or more references to the object in managed code. However, the garbage collector does not recognize references to an object from unmanaged code, and might free objects that are being used exclusively in unmanaged code unless explicitly prevented from doing so. The KeepAlive method provides a mechanism that prevents the garbage collector from collecting objects that are still in use in unmanaged code.

Aside from managed memory allocations, implementations of the garbage collector do not maintain information about resources held by an object, such as file handles or database connections. When a type uses unmanaged resources that must be released before instances of the type are reclaimed, the type can implement a finalizer.

In most cases, finalizers are implemented by overriding the Object.Finalize method; however, types written in C# or C++ implement destructors, which compilers turn into an override of Object.Finalize. In most cases, if an object has a finalizer, the garbage collector calls it prior to freeing the object. However, the garbage collector is not required to call finalizers in all situations; for example, the SuppressFinalize method explicitly prevents an object's finalizer from being called. Also, the garbage collector is not required to use a specific thread to finalize objects, or guarantee the order in which finalizers are called for objects that reference each other but are otherwise available for garbage collection.

In scenarios where resources must be released at a specific time, classes can implement the IDisposable interface, which contains the IDisposable.Dispose method that performs resource management and cleanup tasks. Classes that implement Dispose must specify, as part of their class contract, if and when class consumers call the method to clean up the object. The garbage collector does not, by default, call the Dispose method; however, implementations of the Dispose method can call methods in the GC class to customize the finalization behavior of the garbage collector.

For more information on object finalization and the dispose pattern, see Cleaning Up Unmanaged Resources.

Object aging and generations

The garbage collector in the common language runtime supports object aging using generations. A generation is a unit of measure of the relative age of objects in memory. The generation number, or age, of an object indicates the generation to which an object belongs. Objects created more recently are part of newer generations, and have lower generation numbers than objects created earlier in the application life cycle. Objects in the most recent generation are in generation 0. This implementation of the garbage collector supports three generations of objects, generations 0, 1, and 2. You can retrieve the value of the MaxGeneration property to determine the maximum generation number supported by the system.

Object aging allows applications to target garbage collection at a specific set of generations rather than requiring the garbage collector to evaluate all generations. Overloads of the Collect method that include a generation parameter allow you to specify the oldest generation to be garbage collected.

Disallowing garbage collection

Starting with the .NET Framework 4.6, the garbage collector supports a no GC region latency mode that can be used during the execution of critical paths in which garbage collection can adversely affect an app's performance. The no GC region latency mode requires that you specify an amount of memory that can be allocated without interference from the garbage collector. If the runtime can allocate that memory, the runtime will not perform a garbage collection while code in the critical path is executing.

You define the beginning of the critical path of the no GC region by calling one of the overloads of the TryStartNoGCRegion. You specify the end of its critical path by calling the EndNoGCRegion method.

The following example uses several GC methods to get generation and memory information about a block of unused objects and print it to the console. The unused objects are then collected, and the resulting memory totals are displayed.

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

.NET Framework

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

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

XNA Framework

Supported in: 3.0, 2.0, 1.0

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8

Portable Class Library

Supported in: Portable Class Library

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2015 Microsoft