GC.Collect Metoda

Definice

Vynutí uvolňování paměti.Forces garbage collection.

Přetížení

Collect()

Vynutí okamžité uvolnění paměti pro všechny generace.Forces an immediate garbage collection of all generations.

Collect(Int32)

Vynutí okamžité uvolňování paměti od generace 0 prostřednictvím zadané generace.Forces an immediate garbage collection from generation 0 through a specified generation.

Collect(Int32, GCCollectionMode)

Vynutí uvolňování paměti od generace 0 do zadané generace v čase určeném GCCollectionMode hodnotou.Forces a garbage collection from generation 0 through a specified generation, at a time specified by a GCCollectionMode value.

Collect(Int32, GCCollectionMode, Boolean)

Vynutí uvolňování paměti od generace 0 do zadané generace v čase určeném GCCollectionMode hodnotou s hodnotou, která určuje, zda má být kolekce blokována.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)

Vynutí uvolňování paměti od generace 0 do zadané generace v čase určeném GCCollectionMode hodnotou, s hodnotami, které určují, zda má kolekce blokovat a komprimovat.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()

Vynutí okamžité uvolnění paměti pro všechny generace.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 ()

Příklady

Následující příklad ukazuje, jak použít Collect metodu k provedení kolekce na všech generacích paměti.The following example demonstrates how to use the Collect method to perform a collection on all generations of memory. Kód vygeneruje několik nepoužitých objektů a pak zavolá Collect metodu pro vyčištění z paměti.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
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

Poznámky

Tuto metodu použijte, chcete-li se pokusit uvolnit veškerou paměť, která je nepřístupná.Use this method to try to reclaim all memory that is inaccessible. Provádí blokující uvolňování paměti u všech generací.It performs a blocking garbage collection of all generations.

Všechny objekty bez ohledu na to, jak dlouho jsou v paměti, se považují za kolekce. objekty, které jsou odkazovány ve spravovaném kódu, však nejsou shromažďovány.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. Tuto metodu použijte, chcete-li vynutit, aby systém mohl znovu získat maximální velikost dostupné paměti.Use this method to force the system to try to reclaim the maximum amount of available memory.

Počínaje .NET Framework 4.5.1, můžete zkomprimovat haldu velkých objektů (LOH) nastavením GCSettings.LargeObjectHeapCompactionMode vlastnosti na hodnotu GCLargeObjectHeapCompactionMode.CompactOnce před voláním Collect metody, jak ukazuje následující příklad.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()      

Platí pro

Collect(Int32)

Vynutí okamžité uvolňování paměti od generace 0 prostřednictvím zadané generace.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)

Parametry

generation
Int32

Číslo nejstarší generace, která má být shromážděna z paměti.The number of the oldest generation to be garbage collected.

Výjimky

generation není platné.generation is not valid.

Příklady

Následující příklad ukazuje, jak použít Collect metodu k provedení kolekce v jednotlivých vrstvách paměti.The following example demonstrates how to use the Collect method to perform a collection on individual layers of memory. Kód vygeneruje několik nepoužitých objektů a pak zavolá Collect metodu pro vyčištění z paměti.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();
            }
        }
    }
}
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

Poznámky

Tuto metodu použijte, chcete-li se pokusit uvolnit paměť, která je nepřístupná.Use this method to try to reclaim memory that is inaccessible. Použití této metody však nezaručuje, že všechny nepřístupné paměti v určené generaci jsou uvolněny.However, using this method does not guarantee that all inaccessible memory in the specified generation is reclaimed.

Pokud je implementováno stárnutí objektů, systém uvolňování paměti neshromažďuje objekty s číslem generace, který je vyšší než zadaná generace.If object aging is implemented, the garbage collector does not collect objects with a generation number that is higher than the specified generation. Pokud se stárnutí objektů neimplementuje, systém uvolňování paměti považuje všechny objekty za uvolňování paměti.If object aging is not implemented, the garbage collector considers all objects during the garbage collection.

Pomocí MaxGeneration vlastnosti určete maximální platnou hodnotu generation parametru.Use the MaxGeneration property to determine the maximum valid value of the generation parameter.

Chcete-li, aby systém uvolňování paměti bral v úvahu všechny objekty bez ohledu na jejich generaci, použijte verzi této metody, která nepřijímá žádné parametry.To have the garbage collector consider all objects regardless of their generation, use the version of this method that takes no parameters. Chcete-li, aby systém uvolňování paměti znovu využíval objekty založené na GCCollectionMode nastavení, použijte GC.Collect(Int32, GCCollectionMode) přetížení metody.To have the garbage collector reclaim objects based on a GCCollectionMode setting, use the GC.Collect(Int32, GCCollectionMode) method overload.

Platí pro

Collect(Int32, GCCollectionMode)

Vynutí uvolňování paměti od generace 0 do zadané generace v čase určeném GCCollectionMode hodnotou.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)

Parametry

generation
Int32

Číslo nejstarší generace, která má být shromážděna z paměti.The number of the oldest generation to be garbage collected.

mode
GCCollectionMode

Hodnota výčtu, která určuje, zda je uvolňování paměti vynuceno ( Default nebo Forced ) nebo optimalizované ( Optimized ).An enumeration value that specifies whether the garbage collection is forced (Default or Forced) or optimized (Optimized).

Výjimky

generation není platné.generation is not valid.

-nebo--or- mode není jednou z GCCollectionMode hodnot.mode is not one of the GCCollectionMode values.

Příklady

Následující příklad vynutí uvolnění paměti pro objekty generace 2 s Optimized nastavením.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);
    }
}
Class Program

    Public Shared Sub Main()
        GC.Collect(2, GCCollectionMode.Optimized)
    End Sub
End Class

Poznámky

Použijte mode parametr k určení, zda má být uvolňování paměti provedeno okamžitě, nebo pouze v případě, že je čas optimální pro uvolnění objektů.Use the mode parameter to specify whether garbage collection should occur immediately or only if the time is optimal to reclaim objects. Použití této metody nezaručuje, že všechny nepřístupné paměti v určené generaci jsou uvolněny.Using this method does not guarantee that all inaccessible memory in the specified generation is reclaimed.

Chcete-li upravit rušivé uvolňování paměti během kritických období vaší aplikace, nastavte LatencyMode vlastnost.To adjust the intrusiveness of garbage collection during critical periods in your application, set the LatencyMode property.

Systém uvolňování paměti neshromažďuje objekty s číslem generace vyšším, než je určeno generation parametrem.The garbage collector does not collect objects with a generation number higher than specified by the generation parameter. Pomocí MaxGeneration vlastnosti určete maximální platnou hodnotu generation .Use the MaxGeneration property to determine the maximum valid value of generation.

Chcete-li, aby systém uvolňování paměti bral v úvahu všechny objekty bez ohledu na jejich generaci, použijte verzi této metody, která nepřijímá žádné parametry.To have the garbage collector consider all objects regardless of their generation, use the version of this method that takes no parameters.

Pokud má systém uvolňování paměti uvolnit objekty až do zadané generace objektů, použijte GC.Collect(Int32) přetížení metody.To have the garbage collector reclaim objects up to a specified generation of objects, use the GC.Collect(Int32) method overload. Když zadáte maximální generaci, shromažďují se všechny objekty.When you specify the maximum generation, all objects are collected.

Platí pro

Collect(Int32, GCCollectionMode, Boolean)

Vynutí uvolňování paměti od generace 0 do zadané generace v čase určeném GCCollectionMode hodnotou s hodnotou, která určuje, zda má být kolekce blokována.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)

Parametry

generation
Int32

Číslo nejstarší generace, která má být shromážděna z paměti.The number of the oldest generation to be garbage collected.

mode
GCCollectionMode

Hodnota výčtu, která určuje, zda je uvolňování paměti vynuceno ( Default nebo Forced ) nebo optimalizované ( Optimized ).An enumeration value that specifies whether the garbage collection is forced (Default or Forced) or optimized (Optimized).

blocking
Boolean

true Chcete-li provést blokující uvolňování paměti; false k provedení uvolnění paměti na pozadí, pokud je to možné.true to perform a blocking garbage collection; false to perform a background garbage collection where possible.

Výjimky

generation není platné.generation is not valid.

-nebo--or- mode není jednou z GCCollectionMode hodnot.mode is not one of the GCCollectionMode values.

Poznámky

Následující tabulka shrnuje interakce mode blocking parametrů a:The following table summarizes the interaction of the mode and blocking parameters:

mode blocking je trueblocking is true blocking je falseblocking is false
Forced nebo DefaultForced or Default Blokující kolekce se provádí co nejrychleji.A blocking collection is performed as soon as possible. Pokud probíhá shromažďování na pozadí a generation je 0 nebo 1, Collect(Int32, GCCollectionMode, Boolean) Metoda okamžitě spustí blokující kolekci a vrátí po dokončení kolekce.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. Pokud probíhá shromažďování na pozadí a generation je 2, metoda počká, dokud není dokončeno shromažďování na pozadí, spustí blokující kolekci 2 pro generaci a pak se vrátí.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. Kolekce se provádí co nejrychleji.A collection is performed as soon as possible. Collect(Int32, GCCollectionMode, Boolean)Metoda požaduje kolekci na pozadí, ale není zaručena. v závislosti na okolnostech může být stále prováděna blokující kolekce.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. Pokud kolekce na pozadí již probíhá, metoda se vrátí okamžitě.If a background collection is already in progress, the method returns immediately.
Optimized Blokování kolekce může být provedeno v závislosti na stavu systému uvolňování paměti a generation parametru.A blocking collection may be performed, depending on the state of the garbage collector and the generation parameter. Systém uvolňování paměti se pokusí poskytnout optimální výkon.The garbage collector tries to provide optimal performance. Kolekce může být provedena v závislosti na stavu systému uvolňování paměti.A collection may be performed, depending on the state of the garbage collector. Collect(Int32, GCCollectionMode, Boolean)Metoda požaduje kolekci na pozadí, ale není zaručena. v závislosti na okolnostech může být stále prováděna blokující kolekce.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. Systém uvolňování paměti se pokusí poskytnout optimální výkon.The garbage collector tries to provide optimal performance. Pokud kolekce na pozadí již probíhá, metoda se vrátí okamžitě.If a background collection is already in progress, the method returns immediately.

Pokud volání Collect(Int32, GCCollectionMode, Boolean) metody provede úplné blokující uvolňování paměti, můžete také zkomprimovat haldu velkých objektů nastavením GCSettings.LargeObjectHeapCompactionMode vlastnosti na hodnotu GCLargeObjectHeapCompactionMode.CompactOnce před voláním Collect metody.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.

Platí pro

Collect(Int32, GCCollectionMode, Boolean, Boolean)

Vynutí uvolňování paměti od generace 0 do zadané generace v čase určeném GCCollectionMode hodnotou, s hodnotami, které určují, zda má kolekce blokovat a komprimovat.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)

Parametry

generation
Int32

Číslo nejstarší generace, která má být shromážděna z paměti.The number of the oldest generation to be garbage collected.

mode
GCCollectionMode

Hodnota výčtu, která určuje, zda je uvolňování paměti vynuceno ( Default nebo Forced ) nebo optimalizované ( Optimized ).An enumeration value that specifies whether the garbage collection is forced (Default or Forced) or optimized (Optimized).

blocking
Boolean

true Chcete-li provést blokující uvolňování paměti; false k provedení uvolnění paměti na pozadí, pokud je to možné.true to perform a blocking garbage collection; false to perform a background garbage collection where possible.

compacting
Boolean

true k komprimaci haldy malých objektů; false pouze pro čištění.true to compact the small object heap; false to sweep only.

Poznámky

blockingV případě false , GC rozhodne, zda má být provedeno pozadí nebo blokující uvolňování paměti.If blocking is false, the GC decides whether to perform a background or a blocking garbage collection. compacting true V takovém případě provede blokující uvolňování paměti.If compacting is true, it performs a blocking garbage collection.

compactingV případě true , modul runtime komprimuje haldu pro malé objekty (SoH).If compacting is true, the runtime compacts the small object heap (SOH). Halda rozsáhlých objektů (LOH) není komprimována, pokud GCSettings.LargeObjectHeapCompactionMode vlastnost není nastavena na hodnotu GCLargeObjectHeapCompactionMode.CompactOnce .The large object heap (LOH) is not compacted unless the GCSettings.LargeObjectHeapCompactionMode property is set to GCLargeObjectHeapCompactionMode.CompactOnce. Všimněte si, že to zahrnuje všechny blokující uvolňování paměti, nejen úplné blokování uvolňování paměti.Note that this includes all blocking garbage collections, not just full blocking garbage collections.

Můžete zavolat Collect(Int32, GCCollectionMode, Boolean, Boolean) metodu pro snížení spravované haldy na nejmenší možnou velikost, jak ukazuje následující fragment kódu.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)

Zadání true pro compacting argument garantuje komprimaci, úplné blokování uvolňování paměti.Specifying true for the compacting argument guarantees a compacting, full blocking garbage collection. Nastavením GCSettings.LargeObjectHeapCompactionMode vlastnosti GCLargeObjectHeapCompactionMode.CompactOnce zajistíte komprimaci LOH i SoH.Setting the GCSettings.LargeObjectHeapCompactionMode property to GCLargeObjectHeapCompactionMode.CompactOnce ensures that both the LOH and SOH are compacted.

Platí pro