您的位置:首页 > 其它

.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.

Occupation:

Architect

Company:

http://www.questpond.com
Location:


India

原文地址:http://www.codeproject.com/KB/aspnet/DONETBestPracticeNo2.aspx

如果有什么地方译的不好,不合适,欢迎批评指正,谢谢。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐