.net最佳实践二:使用finalize/dispose模式提升垃圾回收器性能
2009-09-17 17:37
821 查看
本文值得阅读吗?
通过本文你会理解如何通过finalize dispose模式提升GC算法的性能。下图显示完成本文后的对比。class clsMyClass : IDisposable
{
public clsMyClass()
{
}
~clsMyClass()
{
// In case the client forgets to call
// Dispose , destructor will be invoked for
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// Free managed objects.
}
// Free unmanaged objects
}
public void Dispose()
{
Dispose(true);
// Ensure that the destructor is not called
GC.SuppressFinalize(this);
}
}
代码解释:
我们定义了一个带布尔参数的Dispose方法,该参数说明是从Dispose中调用还是从析构函数中调用。如果是从’Dispose’方法调用,则释放所有的托管和非托管的资源。
如果该方法是从析构函数中调用,则只释放非托管的资源。
在dispose方法中我们禁用了finilize的调用,并且用true参数调用了这个dispose方法。
在析构函数中我们使用false值调用dispose函数。换句话说,我们假定GC会处理好托管的资源并用析构函数调用来清理非托管资源。
换句话说,客户端没有调用dispose函数,析构函数会照顾清除非托管资源。
结论
不要在类中写空的析构函数。如果你需要清除,使用带‘SupressFinalize’方法调用的finalize dispose模式。
如果类有公开的dispose方法,确保在客户端代码中调用它。
应用程序应该分配在0代区域中的对象比分配在1代和2代区域中的对象更多。如果在1代和2代区域中有更多的对象,标志着很差的GC算法执行。
源代码
可以在这里找到dispose模式的示例代码License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)About the Author
Shivprasad koirala Member | He thinks he was born for only one mission and thats technology.Keeping this mission in mind he established www.questpond.com where he has uploaded 500 videos on WCF,WPF,WWF,Silverlight,Design pattern, FPA , UML , Projects etc. He is also actively involved in RFC which is a financial open source made in C#. It has modules like accounting , invoicing , purchase , stocks etc.
|
如果有什么地方译的不好,不合适,欢迎批评指正,谢谢。
相关文章推荐
- .Net最佳实践3:使用性能计数器收集性能数据
- .NET性能分析最佳实践之:如何找出使用过多内存的.NET代码(基础篇)
- 对.Net 垃圾回收的C#编程相关方面(Finalize 和Dispose(bool disposing)和 Dispose())的一些理解体会 【zz】
- .NET性能分析最佳实践之:如何找出使用过多内存的.NET代码(进阶篇)
- 对.Net 垃圾回收Finalize 和Dispose的理解
- 对.Net 垃圾回收Finalize 和Dispose的理解
- .net垃圾回收学习【.NET Best Practice No: 2:- Improve garbage collector performance using finalize/dispose pattern】【翻译&&学习】
- 对.Net 垃圾回收的C#编程相关方面(Finalize 和Dispose(bool disposing)和 Dispose())的一些理解体会
- 对.Net 垃圾回收Finalize 和Dispose的理解
- 对.Net 垃圾回收的C#编程相关方面(Finalize 和Dispose(bool disposing)和 Dispose())的一些理解体会
- 对.Net 垃圾回收Finalize 和Dispose的理解
- 对.Net 垃圾回收的C#编程相关方面(Finalize 和Dispose(bool disposing)和 Dispose())的一些理解体会
- [转]对.Net 垃圾回收的C#编程相关方面(Finalize 和Dispose(bool disposing)和 Dispose())的一些理解体会
- 对.Net 垃圾回收的C#编程相关方面(Finalize 和Dispose(bool disposing)和 Dispose())的一些理解体会
- .NET性能分析最佳实践之:如何找出使用过多内存的.NET代码(基础篇)
- .Net最佳实践3:使用性能计数器收集性能数据
- .NET性能分析最佳实践之:如何找出使用过多内存的.NET代码(基础篇)
- 对.Net 垃圾回收的C#编程相关方面(Finalize 和Dispose(bool disposing)和 Dispose())的一些理解体会【个人复习+zz】
- 对.Net 垃圾回收的C#编程相关方面(Finalize 和Dispose(bool disposing)和 Dispose())的一些理解体会(转)
- 使用finalize/dispose 模式提高GC性能(翻译)