元素码农
基础
UML建模
数据结构
算法
设计模式
网络
TCP/IP协议
HTTPS安全机制
WebSocket实时通信
数据库
sqlite
postgresql
clickhouse
后端
rust
go
java
php
mysql
redis
mongodb
etcd
nats
zincsearch
前端
浏览器
javascript
typescript
vue3
react
游戏
unity
unreal
C++
C#
Lua
App
android
ios
flutter
react-native
安全
Web安全
测试
软件测试
自动化测试 - Playwright
人工智能
Python
langChain
langGraph
运维
linux
docker
工具
git
svn
🌞
🌙
目录
▶
C#运行时环境
▶
CLR基础架构
CLR组成与生命周期
托管代码执行流程
应用程序域机制
▶
程序集体系
程序集元数据结构
强名称与版本控制
动态程序集生成
▶
类型系统
CTS核心规范
值类型与引用类型
类型加载与验证
▶
编译与执行
▶
编译过程
从源代码到IL
JIT编译原理
AOT编译机制
▶
执行引擎
方法表结构
栈帧与调用约定
尾调用优化
▶
IL深入解析
IL指令集解析
元数据表结构
调试符号处理
▶
内存管理
▶
垃圾回收
分代回收算法
终结器机制
GC句柄类型
▶
内存模型
托管堆结构
栈内存管理
大对象堆优化
▶
内存优化
内存碎片处理
ArrayPool机制
Span内存视图
发布时间:
2025-03-24 11:03
↑
☰
# 分代回收算法 ## 概述 .NET的垃圾回收器采用分代回收算法来提高回收效率。这种算法基于两个重要的观察结论: 1. 大多数对象的生命周期都很短 2. 存活时间较长的对象往往会继续存活 基于这些特点,CLR将托管堆分为三个代:第0代、第1代和第2代。 ## 分代机制 ### 1. 代的定义 ```csharp public class GenerationalGCExample { public void DemonstrateGenerations() { // 第0代对象 - 新分配的对象 var shortLived = new byte[1000]; // 第1代对象 - 经过一次GC后存活的对象 var mediumLived = new List<int>(); GC.Collect(0); // 触发第0代回收 // 第2代对象 - 经过多次GC后存活的对象 var longLived = new Dictionary<string, object>(); GC.Collect(1); // 触发第1代回收 } } ``` ### 2. 对象晋升 ```csharp public class ObjectPromotionExample { private class SurvivingObject { private byte[] data; public SurvivingObject() { data = new byte[1000]; } public void Simulate() { // 第0代分配 var gen0Before = GC.GetGeneration(this); Console.WriteLine($"初始代数: {gen0Before}"); // 触发GC GC.Collect(0); // 对象晋升到第1代 var gen1After = GC.GetGeneration(this); Console.WriteLine($"GC后代数: {gen1After}"); } } } ``` ## 回收策略 ### 1. 回收触发条件 ```csharp public class GCTriggerExample { public void DemonstrateTriggers() { // 1. 分配触发 var largeArray = new byte[85000]; // 可能触发GC // 2. 显式触发 GC.Collect(); // 触发完整GC // 3. 内存压力触发 var memoryPressure = GC.GetTotalMemory(false); if (memoryPressure > threshold) { GC.Collect(0, GCCollectionMode.Optimized); } } private static long threshold = 100000000; // 100MB } ``` ### 2. 回收过程 ```csharp public class GCProcessExample { public void ExplainGCProcess() { // 1. 标记阶段 var root = new Node() { Next = new Node() { Data = "可达对象" } }; // 2. 压缩阶段 GC.Collect(); GC.WaitForPendingFinalizers(); // 3. 晋升判断 Console.WriteLine($"对象代数: {GC.GetGeneration(root)}"); } private class Node { public Node Next { get; set; } public string Data { get; set; } } } ``` ## 性能优化 ### 1. 代际假设优化 ```csharp public class GenerationalOptimizationExample { public void OptimizeAllocation() { // 1. 对象池化 var pool = new ObjectPool<byte[]>( createFunc: () => new byte[1000], maxObjects: 100); // 2. 大对象处理 var largeObject = new byte[85000]; // 直接分配到LOH // 3. 临时对象优化 using var tempBuffer = new MemoryStream(); ProcessData(tempBuffer); } private void ProcessData(Stream stream) { // 处理数据但不产生过多临时对象 Span<byte> buffer = stackalloc byte[1024]; stream.Read(buffer); } } ``` ### 2. 回收模式选择 ```csharp public class GCModeExample { public void ConfigureGCMode() { // 1. 工作站GC GCSettings.LatencyMode = GCLatencyMode.Interactive; // 2. 服务器GC // 在应用配置文件中设置: // <configuration> // <runtime> // <gcServer enabled="true"/> // </runtime> // </configuration> // 3. 并发GC var isConcurrent = GCSettings.IsServerGC && Environment.ProcessorCount > 1; Console.WriteLine($"使用并发GC: {isConcurrent}"); } } ``` ## 最佳实践 ### 1. 内存管理策略 ```csharp public class MemoryManagementExample { public void ApplyBestPractices() { // 1. 使用using语句 using var resource = new DisposableResource(); resource.Process(); // 2. 避免终结器 var noFinalizer = new ResourceWithoutFinalizer(); // 3. 实现IDisposable public class DisposableResource : IDisposable { private bool disposed = false; private IntPtr handle; protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { // 释放托管资源 } // 释放非托管资源 if (handle != IntPtr.Zero) { Marshal.FreeHGlobal(handle); handle = IntPtr.Zero; } disposed = true; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } } } ``` ### 2. 性能监控 ```csharp public class GCMonitoringExample { public void MonitorGCPerformance() { // 1. GC事件监听 GC.RegisterForFullGCNotification( maxGenerationThreshold: 9, largeObjectHeapThreshold: 9); // 2. 性能计数器 using var gcCounter = new PerformanceCounter( ".NET CLR Memory", "# Gen 0 Collections", Process.GetCurrentProcess().ProcessName); // 3. 内存使用分析 var before = GC.GetTotalMemory(false); ProcessLargeData(); var after = GC.GetTotalMemory(false); Console.WriteLine($"内存增长: {after - before} bytes"); } private void ProcessLargeData() { // 处理大量数据的业务逻辑 } } ``` ## 总结 分代回收算法是.NET中非常重要的内存管理机制,它通过: 1. 分代管理 - 按对象年龄分类 - 优化回收效率 - 减少内存碎片 2. 智能优化 - 自适应回收 - 并发回收 - 大对象处理 3. 性能提升 - 减少暂停时间 - 提高吞吐量 - 优化内存使用 通过合理使用分代回收机制,我们可以: - 提高应用性能 - 减少内存压力 - 优化资源使用 - 提升用户体验