Do I need to embed or complete my objects?

For too long, I let the garbage collector do the magic, taking off all responsibilities.

Unfortunately, this never turned into a problem ... Therefore, I no longer thought about it.

Now that I think about it, I really don’t understand what the "dispose" function really does, and how and when it should be implemented.

The same question for finalizing ...

And the last question ... I have a pictureManipulation class: when I need to save / resize / resize ... I start a new instance of this class using its objects, and ... well let the garbage collection kill the instance

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?
}
+3
source share
3

class Student

Dispose()?

, 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 . () , .

+3

Dispose, , DB, .., , , IDisposable. , Dispose:

  • IDisposable (, DB), IDisposable finalizer
  • IDisposable, Dispose() Dispose
  • , , ( ), .
  • , Dispose (bool).
+3

, , , .

, , , , : , , GC .

To learn how to do this correctly, read the disposal and finalization guides, as well as the use () {} clause.

+1
source

Source: https://habr.com/ru/post/1760256/


All Articles