Finalization

There is an obvious problem with using automatic memory management in conjunction with pointers to unmanaged resources: when components hold references to nonmanaged resources that need to be explicitly disposed of, it is necessary to make sure that the resource is disposed of before the object is collected. The CLI supports a concept called finalization to solve this problem. Finalizable objects are placed on a special weak reference list when created. The collector monitors this list and when all strong references to a finalizable object are released, moves the reference from the weak list to the finalization queue, which continues to keep the object alive. (We saw the finalization queue appear in numerous scan examples earlier in this chapter.) The finalization thread will go though the list of objects in a lazy fashion and call the finalization method on each object. If an object does not become reachable again as a result of being finalized (remember, arbitrary code is being run within the finalization method that can reestablish references!), the finalization reference will be released, and the object will be collected in a normal fashion.

Note

One interesting issue for programmers is that garbage collection happens at unpredictable times, depending on the algorithm and the load. Because of this, it is sometimes desirable to go beyond finalization and revert to an old-fashioned disposal pattern, in which programmers are required to explicitly “close” resources ...

Get Shared Source CLI Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.