AGENDA
FunctionFeatureManaged HeapSmall Object Heap (SOH)Large Object Heap (LOH)Collection With Finalization QueueCollection TimingStrong reference & Week referenceGC ModeReferenceQ & A
3
FUNCTION
Automatic memory management Responsible for reclaiming the memory of no longer used
objects.
5
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
MANAGED HEAP
A series of allocated memory segments (approx 16Mb in size each) to store and manage objects
9
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
PROMOTIONS
Objects that are not reclaimed in a garbage collection are known as survivors, and are promoted to the next generation.
12
COLLECTION TIMING
Low physical memory. The memory allocated on the managed heap
surpasses an acceptable threshold. Invoke System.GC.Collect.
22
STRONG REFERENCE & WEEK REFERENCE
Week reference A reference that does not protect the referenced
object from collection by a garbage collector.
24
STRONG REFERENCE & WEEK REFERENCEusing 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
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
REFERENCE
Garbage Collection https://msdn.microsoft.com/en-us/library/0xy59w
tx(v=vs.110).aspx .NET 的自動記憶體管理
https://msdn.microsoft.com/zh-tw/library/dd229208.aspx?f=255&MSPPError=-2147217396
.Net Garbage Collection in depth http://www.dotnet-tricks.com/Tutorial/netframew
ork/0L3P131012-.Net-Garbage-Collection-in-depth.html
29
REFERENCE
Understanding .NET Garbage Collection http://www.telerik.com/blogs/understanding-net-
garbage-collection
30