Will implementing the IDisposable interface move the object to the Finalize list?

StackOverflow https://stackoverflow.com/questions/9169255

  •  26-04-2021
  •  | 
  •  

سؤال

I am reading now about the Dispose and the Finalize method on the CLR ( 4.0 ) I dont understand something ...

If I add an implementation of Finalize ( ~className1 ) to my code => then the Finalize List have pointer to the object instance that in the managed heap.

Now, Lets say i did not implement the Finalize ( ~className2 ) and i just implemented the IDisposable interface on my code - Is thie object will have pointer from the Finalize List ?

هل كانت مفيدة؟

المحلول

No. If an object doesn't have a finalizer, it will not be in the finalize queue.

Reference: MSDN

The garbage collector keeps track of objects that have Finalize methods... Each time your application creates an object that has a Finalize method, the garbage collector places an entry in the finalization queue that points to that object.

نصائح أخرى

Basically, the longer an object exists, the less the garbage collector will check whether it's still referenced in the code. That means that unused objects can often still be in memory although they haven't been referenced anymore for a long time. Also, if you want to explicitly tell an object to clean up its resources, use the Dispose method. I'd suggesst calling GC.SuppressFinalize(this) in its implementation, and calling the Dispose method in the finalizer as well. That way, if the user forgets to call Dispose, which should not but can happen, the object's resources will get freed-up eventually.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top