Practical Memory Management

本文介绍如何利用访问器方法来简化内存管理任务,并减少内存管理中常见的问题。推荐使用访问器方法设置属性值,避免在初始化方法和dealloc方法中使用访问器方法。文章还讨论了如何使用弱引用避免内存循环引用等问题。

Use Accessor Methods to Make Memory Management Easier:

一般使用accessor method 来大幅度减少内存管理出现的问题,相比直接使用retain和release来说。

@interface Counter: NSObject{

NSNumber *_count;

}

@property (nonatomic, retain) NSNumber *count;

 

“get”accessor Method:

- (NSNumber *)count{

return _count;

}

 

“set”accessor Method:

- (void)SetCount: (NSNumber *)newCount{

[newCount retain];

[_count release];

_count = newCount; //Make the new assignment;

}

 

Use Accessor Methods to Set Property Values:

推荐使用:

-(void)reset{

NSNumber *zero = [[NSNumber alloc] initWithInteger:0];

[self setCount:zero];

[zero release];

}

-(void)reset{

NSNumber *zero = [NSNumber numberWithInteger:0];

[self setCount:zero];

}

 

不推荐使用(将不遵从KVO):

-(void)reset{

NSNumber *zero = [[NSNumber alloc] initWithInteger:0];

[_count release];

_count = zero;

}

 

Do not Use Accessor Methods in Initializer Method and dealloc

Use Weak References to Avoid Retain Cycles:

"父"对象保持对"子"对象的强引用,"子"对象保持对"父"对象的弱引用,以避免出现Retain Cycles.

retaincycles

Cocoa 的弱引用包含但不限于: table data sources, outline view items, notification observers, miscellaneous targets and delegates.在弱引用时,send message 时需要特别小心对象是否有效。

Avoid Causing Deallocation of Objects You’re Using:

1. 当一个对象从基本的集合类里移除的时候,这个对家就会被马上释放掉,如果这个集合是这个对象的唯一owner的话

heisenObject = [array objectAtIndex:n];

[array removeObjectAtIndex:n]; //heisenObject could now be invalid.

2. 当“parent obejct”释放时,“children object” 也会释放

id parent = <#create o parent object#>;

// …

hesienObject = [parent child];

[parent release];//Or, for example: self.parent = nil;

//heisenObject could now be invalid.

通过retain你接收到的对象,然后在用完后,release这个对象,来避免出现上述的情况:

hesienObject = [[array objectAtIndex: n] retain];

[array removeObjectAtIndex:n];

//Use hesienObject….

[hesienObject release];

Do not Use dealloc to Manage Scarce Resources:

三种情况:

1. 依赖于对象的消除顺序的

2. 稀缺资源不能回收

3. cleanup 的逻辑在错误的线程执行

 

Collections Own the Objects They Contain:

给集合(如array, dictionary,set)添加一个项时,不需要retain,当从一个集合移除一个项时,也不需要release.

转载于:https://www.cnblogs.com/agefisher/archive/2012/06/15/2550600.html

<think>Hmm, the user is asking about configuring snapshot parameters in Net Memory 5.0 for handle leak analysis. Let me break this down carefully. First, I notice the user has provided several references about .NET memory leaks and GDI handle leaks. The core question seems very specific - how to set snapshot parameters in this particular tool. The user must be troubleshooting a production issue and needs precise guidance. Looking at the context clues: the references mention WPF memory leaks, GDI handle tracking, and .NET resource management. This suggests the user is likely dealing with a Windows desktop application (probably WPF or WinForms) experiencing resource exhaustion. The mention of "wProcessId" and memory offsets in reference [2] indicates they've been digging into low-level diagnostics already - so they're technically proficient. The key requirements I need to address: - Exact snapshot configuration steps for handle tracking - Parameters that isolate handle-related data - How to capture meaningful comparisons (since leaks show in delta between snapshots) I recall Net Memory's architecture: it uses two snapshot modes - one for heap memory and another for handles/resources. For handle leaks, we need to configure the "System Information" capture to include handles and GDI objects specifically. The user might not realize that the default settings often omit critical handle data. Important technical considerations: 1) Must enable "Capture kernel object handles" - this includes mutexes, files etc. 2) Should activate "GDI object tracking" separately (as it's disabled by default) 3) Need to set appropriate depth for handle stacks (recommend at least 5 frames) 4) Memory thresholds should be lowered to catch small leaks The user seems time-pressed - they didn't ask for theory but practical steps. I'll structure the answer as numbered configuration points with brief justifications. Should also mention the critical post-snapshot step: comparing two snapshots with the "Handles" view active, sorted by creation time. Better include a warning about common pitfalls too - like forgetting to disable symbol server during capture (causes timeouts) or not setting working directory for PDBs. Oh and must emphasize running as admin - otherwise handle enumeration fails silently. For the related questions section, I'll focus on next-step diagnostics: how to interpret handle ownership chains, spot suspicious patterns, and differentiate between actual leaks vs. caching. The user will likely face these challenges after capturing the snapshots.</think>在 Net Memory 5.0 中分析句柄泄露时,正确设置快照参数需遵循以下步骤: ### 关键配置步骤 1. **启动应用程序** - 通过 Net Memory 启动目标进程(`File` → `Start New Application`) - 或附加到正在运行的进程(`File` → `Attach to Running Process`) 2. **配置快照捕获参数** ```plaintext [Snapshot] → [Snapshot Configuration] ``` - ✅ **勾选关键项目**: - `Kernel Objects`(内核对象句柄) - `GDI Objects`(GDI 图形句柄) - `User Objects`(用户对象句柄) - `Handles`(包含所有句柄类型) - ⚙️ **堆栈跟踪设置**: - 设置 `Stack depth` ≥ 5(建议 7-10) - 启用 `Capture stack traces for object allocations` - 📊 **内存阈值**: - 降低对象大小过滤阈值(例如设为 0 KB)避免遗漏小对象泄露 3. **执行快照捕获** - 初始快照:应用启动后立即拍摄(基线) - 增量快照:执行可疑操作后拍摄(建议 2-3 次) ```plaintext [Take Snapshot] 或快捷键 Ctrl+Shift+S ``` 4. **对比分析泄露** ```plaintext [Compare Snapshots] → 选择两个时间段快照 ``` - 在 `Handles` 视图排序 `Delta` 列 - 检查 `Handle Type` 列识别泄露类型(如 `GDI32!HPALETTE`) - 双击高增量条目查看创建堆栈跟踪[^2] ### 注意事项 1. **符号路径配置** - 在 `Symbols` 标签添加 PDB 符号路径,确保正确解析堆栈 - 启用 `Microsoft Symbol Servers`(需联网) 2. **运行权限** - 以**管理员身份**运行 Net Memory,否则可能无法捕获完整句柄信息 3. **典型泄露特征** ```plaintext GDI 泄露:GDIxxx 类型句柄持续增长 内核对象泄露:Event/Mutex/File 句柄异常增加 ``` 通过 `Group by Handle Type` 可快速定位问题类型[^1] 4. **避免误判** - 排除应用正常缓存(如重复创建/销毁的资源池) - 关注未释放的**非托管资源**(通过 `Finalizer` 队列验证) --- ### 相关问题 1. Net Memory 5.0 分析句柄泄露时,如何区分 GDI 泄露与内核对象泄露? 2. 当堆栈跟踪显示在系统 DLL 中(如 `user32.dll`),如何定位实际泄露代码? 3. 对于间歇性句柄泄露,应该采取哪些特殊的快照策略? 4. 如何验证发现的句柄泄露是否确实由 .NET 代码引起?[^3] [^1]: 引用自 WPF 内存泄露分析文档,涉及句柄类型识别 [^2]: 参考 GDI 句柄调试案例中通过内存偏移定位的方法 [^3]: 基于 .NET 资源泄露解决方案中关于托管/非托管资源判别的原则
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值