c# - 我是否需要在我的对象中实现处置或终结?

标签 c# dispose garbage-collection finalize

长期以来,我让垃圾收集器发挥其魔力,卸下了我自己的所有责任。

可悲的是,它从来没有变成一个问题......所以我从来没有再考虑过这个问题。

现在,当我想到它时,我真的不明白“dispose”函数到底做了什么,以及应该如何以及何时实现它。

finalize 的相同问题...

最后一个问题... 我有一个 pictureManipulation 类:当我需要保存/调整大小/更改格式时......我启动该类的一个新实例使用它的对象......好吧让垃圾收集杀死实例

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)学生

Do I need a 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(){} block ,只需在完成后调用 a.Dispose(); .

但请注意,这里(远)更好的设计是避免将图片对象保留在 Student 对象中。这引发了整个责任链。

Do I need a Finalizer?

。因为当收集 Student 对象时,保证在同一次运行中收集其 studentPic 对象。 Finalizer(析构函数)将毫无意义但仍然很昂贵。

关于c# - 我是否需要在我的对象中实现处置或终结?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3510513/

相关文章:

c# - 我怎样才能在鼠标输入事件中做到这一点,新的表单/用户控件将移动到 Form1 的中心?

c# - 如果关联的 SqlConnection 将被处置,是否需要 SqlCommand.Dispose()?

javascript - dc.js:dispose() 和 deregisterChart() 的问题

c# - Garbage Collection Modes : If 2 apps exist on a server, "Server Mode"难道是劫以还债?

C# 库做 fft 和 ifft?

c# - 使用 LINQ 解析 XML 并填充现有对象的属性而不是创建新的属性

c# - 在使用 block 或使用 block 声明中声明 IDisposable 成员的区别?

c - Boehm GC如何为C程序工作?

ios - 我是否应该处理 UIImageView 的 Image 属性以帮助 Monotouch 中的垃圾收集器?

c# - 我的 DAL 应该返回 Person 还是 Datatable?