I was reading this MSDN reference:
Although the garbage collector is able
to track the lifetime of an object
that encapsulates an unmanaged
resource, it does not have specific
knowledge about how to clean up the
resource. For these types of objects,
the .NET Framework provides the
Object.Finalize method, which allows
an object to clean up its unmanaged
resources properly when the garbage
collector reclaims the memory used by
the object. By default, the Finalize
method does nothing. If you want the
garbage collector to perform cleanup
operations on your object before it
reclaims the object's memory, you must
override the Finalize method in your
class.
I understand how GC works but this give me a thought that what is actually CleanUp? Is it just reclaiming memory if it is than why it is having different name?
Answer
They used a generic phrase such as "clean up" because other things may need to be done besides just reclaiming memory. I can see how this may be a little confusing, since the quote mentions cleaning up resources and reclaiming memory in the same sentence. In that case, what they mean is that the garbage collector reclaims the memory used by the managed code that actually called into an unmanaged library (a wrapper class, for example), but leaves the unmanaged-specific reclamation process up to the developer (closing file handles, freeing buffers, etc).
As an example, I have a Graphviz wrapper library containing a Graph
class. This class wraps the functions used to create graphs, add nodes to them, etc. Internally, this class maintains a pointer to an unmanaged graph structure allocated by Graphiz itself. To the .NET Framework, this is merely an IntPtr
and it has no idea how to free it during garbage collection. So, when a managed Graph
object is no longer being used, the garbage collector frees up the memory used by the pointer, but not the data it points to. To do this, I have to implement a finalizer that calls the unmanaged function agclose
(the Graphviz function that releases the resources used by a graph).
No comments:
Post a Comment