This document provides an overview of garbage collection in .NET. It discusses the managed heap which stores objects and is divided into generations for younger and older objects. The large object heap stores larger objects separately. Garbage collection reclaims unused memory and objects are promoted between generations or finalized if they implement IDisposable. Collection can occur due to low memory or manually. Strong references protect objects while weak references allow collection. Garbage collection can run concurrently or in parallel depending on configuration.
7. FEATURE
Allow us to develop an application without having
worry to free memory.
Allocates memory for objects efficiently on the
managed heap.
Reclaims the memory for no longer used objects
and keeps the free memory for future allocations.
Provides memory safety by making sure that an
object cannot use the content of another object.
7
11. GENERATIONS
Generation 0
The youngest generation and contains short-lived
objects.
About 256 KB
Generation 1
Contains short-lived objects and serves as a buffer
between short-lived objects and long-lived objects.
About 2MB
Generation 2.
Contains long-lived objects.
About 10MB
11
12. PROMOTIONS
Objects that are not reclaimed in a garbage
collection are known as survivors, and are
promoted to the next generation.
12
24. STRONG REFERENCE & WEEK REFERENCE
Week reference
A reference that does not protect the referenced object
from collection by a garbage collector.
24
25. STRONG REFERENCE & WEEK REFERENCE
using System;
public class Program {
public static void Main() {
var person1 = new Person("Larry");
var person2 = new WeakReference(null);
person2.Target = new Person("Jack");
GC.Collect();
var jack = person2.Target as Person;
Console.WriteLine(person1.Name);
Console.WriteLine(jack == null ? "(null)" : jack.Name);
}
}
public class Person {
public string Name { get; private set; }
public Person(string name) {
this.Name = name;
}
}
25
person1
person2
Larry
Heap
Jack
Strong Reference
Week Reference
person1 Larry
Heap
Strong Reference
GC
27. GC MODE
Workstation GC
Default GC mode.
Server GC
Available only on multiprocessor computers.
Creates a separate managed heap and thread for each
processor and performs collections in parallel.
ASP.NET and SQL Server enable.
27