Clean Up Vs Memory Reclaim in .Net
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?
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).
Beware that this is not the full story either, as finalizing only occurs when the object is garbage collected. In actual fact you should release all unmanaged resources (file handles, mutexes, unmanaged memory) as soon as possible. You should have a look at the IDisposable
interface, which defines the Dispose()
function.
Wherever possible your disposer should run the same method to free resources as the finalizer would, but then call GC.SuppressFinalize()
to stop it from running again (in the finalizer), as there is a minor performance hit when using objects that implement finalizers.
An example would be if you wrote a component that used some operating system resource like named pipe or memory mapped file. You could used the finalize operation to release the resource back to the os.
链接地址: http://www.djcxy.com/p/54504.html下一篇: 在.Net中清理Vs内存回收