Finalization

In general, there is no need for your object to know when it is being garbage-collected. All subordinate objects that your object references will themselves be automatically reclaimed as part of normal GC operation.

The preferred mechanism for triggering the execution of cleanup code is to use a termination handler. Termination handlers protect a range of instructions inside a method by guaranteeing that a “handler” block will execute prior to leaving the protected range of instructions. This mechanism is exposed to C# programmers via the tryfinally construct discussed in Chapter 6.

Despite the existence of the termination handler mechanism, old habits often die hard, and programmers who cut their teeth on C++ are accustomed to ...

Get Essential .NET, Volume 1: The Common Language Runtime 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.