views:

115

answers:

2

I have been pondering why it is recommended that we should not release managed resources inside finalize. If you see the code example at http://msdn.microsoft.com/en-us/library/system.gc.suppressfinalize.aspx , and search for string "Dispose(bool disposing) executes in two distinct scenarios" and read that comment, you will understand what I mean.

Only possibility I can think of is that it probably has something to do with the fact that it is not possible to predict when finalizer will get called. Does anyone know the right answer ?

thanks, mishal

+5  A: 

If you're referencing another object from the finalizer, you don't know if that object has always been finalized - and how it will behave if it is finalized. (I don't know whether any current CLR runs multiple finalizer threads, but another scary possibility is that it's in the process of being finalized when your finalizer runs.)

All you should need to do in a finalizer is release unmanaged resources that you own directly. If you're referencing other managed types which own resources, let them do their job in their finalizers.

Jon Skeet
But if my object (which is currently getting finalized) is holding a reference to the other managed object, I think CLR ensures that the referenced object is alive at this stage. (im just guessing by the concept of garbage collection, that as long asan object is referenced it will not get cleaned up)
mishal153
But if my object (which is currently getting finalized) is holding a reference to the other managed object, I think CLR ensures that the referenced object is alive at this stage. (im just guessing by the concept of garbage collection, that as long asan object is referenced it will not get cleaned up). So it would be a CLR bug i think if the referenced object is already finalized before the parent object is finalized.
mishal153
As long as an object is *reachable*, it won't be cleaned up. If your object is being finalized, then it isn't reachable, and any references it's holding aren't either (and thus don't count).
cHao
ohhh ok.. makes sense. thanks :)
mishal153
A: 

I think you've pretty much hit the nail on the head. If you look at the wording in the Object.Finalize documentation, it says: See the IDisposable interface for a complementary and more controllable means of disposing resources. "Complementary" meaning, "another way to do it," and controllable being..exactly what you said.

Edit: And what Jon Skeet said. The notion of multiple finalizer threads has ensured I will either not be sleeping, or having very bad dreams tonight.

Marc Bollinger