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 try–finally 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access