Module 7: The Garbage Collector (The Cleanup Crew)
📚 Module 7: The Garbage Collector (GC)
Course ID: DOTNET-105
Subject: The Cleanup Crew
In .NET, you don’t have to manually delete your objects like in C++. The Garbage Collector does it for you.
🏗️ Step 1: Generations (The “Ages” of Data)
The GC organizes objects into three generations based on how long they live.
🧩 The Analogy: The Coffee Shop Seating
- Gen 0 (Quick Sip): People who come in, drink a coffee, and leave in 5 minutes. (Local variables).
- Gen 1 (The Laptop Worker): People who stay for an hour.
- Gen 2 (The Manager): People who stay all day. (Global settings, Caches).
Why do we do this? Because it’s much faster to check the “Quick Sip” area than the whole shop. The GC cleans Gen 0 thousands of times a day, but only cleans Gen 2 once in a while.
🏗️ Step 2: The “Stop-the-World” Event
When the GC runs a major cleanup, it has to pause your app for a tiny fraction of a second.
🧩 The Analogy: The Janitor
Imagine a school hallway. To mop the floor, the janitor has to ask the kids to stop running for 10 seconds.
- Senior Goal: Design your code so the janitor doesn’t have to mop very often (Zero-Allocation code).
🏗️ Step 3: Finalizers vs. Dispose
- Finalizer: The GC cleans it eventually. (Slow).
- Dispose: You clean it Right Now. (Fast).
In Code:
using (var file = File.Open("log.txt")) {
// Done! The 'using' block calls Dispose() immediately.
}🥅 Module 7 Review
- GC: Automatic memory management.
- Generations 0, 1, 2: Sorting data by how long it lives.
- Heap: Where the objects live.
- Dispose: Telling the GC you are finished early.