
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
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
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(); } } }
- Related Articles
- Garbage collection in Java
- Garbage Collection in Python
- Java Garbage collection
- How does garbage collection work in Python?
- Garbage collection(GC) in JavaScript?
- How does Garbage Collection work in Lua Programming?
- Destroying Objects (Garbage Collection) in Python
- What is garbage collection in C#?
- Destructors and Garbage Collection in Perl
- What is JavaScript garbage collection?
- How to make an object eligible for garbage collection in Java?
- How to prevent object of a class from garbage collection in Java?
- How can we call garbage collection (GC) explicitly in Java?
- Using the finalize() method in Java Garbage Collection
- Explain in detail about Reference-counting garbage collection in JavaScript?

Advertisements