![](/img/trans.png)
[英]Do I implement my own Dispose() or do I use Finalize() for .NET 3.5 RNGCryptoServiceProvider?
[英]Do I need to implement a dispose or finalize in my objects?
太久了,我让垃圾收集器发挥其魔力,消除了我自己的所有责任。
可悲的是,它从未变成一个问题......所以我从来没有再考虑过这个问题。
现在,当我想到它时,我并不真正理解“dispose”函数的真正作用以及它应该如何以及何时实现。
完成同样的问题......
最后一个问题......我有一个类图片操作:当我需要保存/调整大小/更改格式时...我启动该类的一个新实例使用它的对象...好吧让垃圾收集杀死实例
class student
{
public void displayStudentPic()
{
PictureManipulation pm = new PictureManipulation();
this.studentPic = pm.loadStudentImage(id);
}
}
Class Test
{
student a = new Student();
a.displayStudentPic();
// Now the function execution is ended... does the pm object is dead? Will the GC will kill it?
}
关于你的class Student
我需要
Dispose()
吗?
假设Picture类是IDisposable: 是的 。 因为Student对象'拥有' studentPic
并且负责清理它。 最小的实现:
class Student : IDisposable
{
private PictureClass studentPic;
public void Dispose()
{
if (studentPic != null)
studentPic.Dispose();
}
...
}
现在,您使用Student对象,如:
void Test
{
using (Student a = new Student())
{
a.displayStudentPic();
} // auto Dispose by using()
}
如果你不能/不使用using(){}
块,只需调用a.Dispose();
当你完成它。
但请注意,这里(远)更好的设计是避免将图片对象保留在Student对象中。 这引发了一系列责任。
我需要定型器吗?
不 。 因为在收集Student对象时,保证在同一次运行中收集其studentPic对象。 Finalizer(析构函数)毫无意义但仍然很昂贵。
如果您的类型包含一些非托管资源(如数据库连接,文件句柄等),或者您的类型所持有的某些对象实现了IDisposable接口,则只需要实现Dispose方法。 在实现标准Dispose模式时,您应该考虑以下几点:
如果它拥有除了对象本身所拥有的内存之外的资源,则需要注意对象处理。
例如,如果您的对象抽象文件,您必须在文件发布时处于控制状态,或者,您将非常糟糕:您的应用程序已完成使用它并且它仍将被锁定,直到GC处理您的对象。
要了解如何正确执行此操作,请阅读有关dispose和finalize的手册以及using(){}子句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.