GC.Collect Method ()
Forces garbage collection of all generations.
[Visual Basic] Overloads Public Shared Sub Collect() [C#] public static void Collect(); [C++] public: static void Collect(); [JScript] public static function Collect();
Remarks
Use this method to attempt to reclaim all memory that is inaccessible. However, the Collect method does not guarantee that all inaccessible memory is reclaimed.
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 attempt to reclaim the maximum amount of available memory.
Example
[Visual Basic] Imports System Namespace GCCollect_Example 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}", GC.GetTotalMemory(False)) 'Collect all generations of memory. GC.Collect() Console.WriteLine("Memory used after full collection: {0}", 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 i End Sub End Class End Namespace [C#] using System; namespace GCCollectExample { class MyGCCollectClass { private const int maxGarbage = 1000; static void Main() { // Put some objects in memory. MyGCCollectClass.MakeSomeGarbage(); Console.WriteLine("Memory used before collection: {0}", GC.GetTotalMemory(false)); // Collect all generations of memory. GC.Collect(); Console.WriteLine("Memory used after full collection: {0}", GC.GetTotalMemory(true)); } static 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(); } } } } [C++] #using <mscorlib.dll> 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 = new Version(); } } int main() { // Put some objects in memory. MakeSomeGarbage(); Console::WriteLine(S"Memory used before collection: {0}", __box(GC::GetTotalMemory(false))); // Collect all generations of memory. GC::Collect(); Console::WriteLine(S"Memory used after full collection: {0}", __box(GC::GetTotalMemory(true))); }
[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button
in the upper-left corner of the page.
Requirements
Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework
See Also
GC Class | GC Members | System Namespace | GC.Collect Overload List