Finalizers

When implementing your own types, you can choose to give them finalizers (by providing C# destructors). Finalizers are methods called asynchronously by the GC once an object is determined to be garbage.

Although this is required in certain cases, in general there are many good technical reasons to avoid the use of finalizers.

As described in the previous section, objects with finalizers incur significant overhead when they are collected, requiring asynchronous invocation of their Finalize methods and taking two full GC cycles for their memory to be reclaimed.

Other reasons not to use finalizers include:

  • Objects with finalizers take longer to allocate on the managed heap than objects without finalizers.

  • Objects with finalizers that refer to other objects (even those without finalizers) can prolong the life of the referred objects unnecessarily.

  • It’s impossible to predict in what order the finalizers for a set of objects will be called.

  • You have limited control over when (or even if!) the finalizer for an object will be called.

In summary, finalizers are somewhat like lawyers — while there are cases in which you really need them, in general you don’t want to use them unless absolutely necessary. If you do use them, you need to be 100 percent sure you understand what they are doing for you.

If you have to implement a finalizer, follow these guidelines or have a very good reason for not doing so:

  • Ensure that your finalizer executes quickly.

  • Never block in your finalizer.

  • Free any unmanaged ...

Get C# in a Nutshell 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.