开发者

Destruction of .NET Objects by CLR

开发者 https://www.devze.com 2023-02-11 22:23 出处:网络
How is any .NET object without any dispose() or开发者_如何学编程 finalize pattern destroyed by clr?

How is any .NET object without any dispose() or开发者_如何学编程 finalize pattern destroyed by clr? is it cleared by the Object Finalize Method!


No, if the object does not declare an explicit finalizer it is never added to the freachable queue - its memory is simply reclaimed.

This is one of the reasons that you should not declare a finalizer unless you really need one. Any objects that have finalizers require two passes of the GC to be fully collected.


From Object.Finalize:

Object.Finalize does nothing by default. It must be overridden by a derived class only if necessary, because reclamation during garbage collection tends to take much longer if a Finalize operation must be run.

Also I would recommend that you check out Garbage Collection: Automatic Memory Management in the Microsoft .NET Framework.


See this article to get a good overview of what the Dispose pattern does.

In some cases, you might want to provide programmers using an object with the ability to explicitly release these external resources before the garbage collector frees the object. If an external resource is scarce or expensive, better performance can be achieved if the programmer explicitly releases resources when they are no longer being used.


The Garbage Collector will eventually reclaim the memory used by an object, after it can no longer be reached by any references. This is the only cleanup that will occur unless the object has a finalizer.


It's probably simplest to imagine the garbage collector in .net as operating in a way similar to the way a bowling-alley pinsetter clears out "deadwood" (knocked-over pins):

  1. Move all of the pins which should not be cleared out (i.e. the ones which are still standing) off the surface of the alley.
  2. Run the sweeper across the whole surface of the alley, clearing out wholesale anything that was there.
  3. Put the pins back.

Note that at no stage of the operation does the pinsetter detect or target any of the knocked-over pins. It neither knows nor cares whether there is one such pin or nine of them (if no pins are standing, the pinsetter will register a strike and skip the second half of a frame). From the standpoint of the pinsetter, those pins may as well not exist until such time as they reach the mechanism that can recycle them.

0

精彩评论

暂无评论...
验证码 换一张
取 消