How to force garbage collection in C#?


Yes it is possible to force garbage collector in C# to run by calling Collect() method

This is not considered a good practice because this might create a performance over head. Collect() Forces an immediate garbage collection of all generations.

Collect(Int32)Forces an immediate garbage collection from generation 0 through a specified generation.

Example

 Live Demo

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

Updated on: 19-Aug-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements