Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to force garbage collection in C#?
The garbage collector in C# automatically manages memory by removing unused objects. However, you can force garbage collection to run immediately using the GC.Collect() method, though this is generally not recommended due to performance implications.
Forcing garbage collection should only be used in specific scenarios where you know large amounts of memory have been freed and want to clean up immediately, such as after closing a large document or completing a memory-intensive operation.
Syntax
Following is the syntax for forcing garbage collection −
GC.Collect();
To collect specific generations −
GC.Collect(int generation);
GC.Collect() Methods
| Method | Description |
|---|---|
GC.Collect() |
Forces immediate garbage collection of all generations (0, 1, and 2) |
GC.Collect(int generation) |
Forces garbage collection from generation 0 through the specified generation |
GC.WaitForPendingFinalizers() |
Waits for finalizers to complete before continuing |
Basic Example
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));
// Force garbage collection of all generations
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
The output of the above code is −
Memory used before collection: 79,168
Memory used after full collection: 78,800
Generation-Specific Collection
The .NET garbage collector uses three generations (0, 1, 2). You can target specific generations for collection −
using System;
class GenerationExample {
static void Main() {
// Create some objects
CreateObjects();
Console.WriteLine("Memory before any collection: {0:N0}", GC.GetTotalMemory(false));
// Collect only generation 0
GC.Collect(0);
Console.WriteLine("Memory after Gen 0 collection: {0:N0}", GC.GetTotalMemory(false));
// Collect all generations
GC.Collect();
Console.WriteLine("Memory after full collection: {0:N0}", GC.GetTotalMemory(true));
}
static void CreateObjects() {
for(int i = 0; i
The output of the above code is −
Memory before any collection: 86,432
Memory after Gen 0 collection: 86,168
Memory after full collection: 85,936
Best Practices
-
Avoid calling GC.Collect() in normal application flow as it can hurt performance.
-
Use it only after major operations that free large amounts of memory.
-
Consider calling
GC.WaitForPendingFinalizers()afterGC.Collect()for objects with finalizers. -
Monitor memory usage with
GC.GetTotalMemory()to verify collection effectiveness.
When to Use Forced Collection
Forced garbage collection might be appropriate in these scenarios −
-
After closing large documents or datasets
-
Before starting memory-intensive operations
-
In testing scenarios to ensure consistent memory states
-
After unloading plugins or assemblies
Conclusion
While C# provides GC.Collect() to force garbage collection, it should be used sparingly as it can impact performance. The garbage collector is highly optimized and typically knows best when to run. Use forced collection only in specific scenarios where you've freed large amounts of memory and want immediate cleanup.
