[ Team LiB ] Previous Section Next Section

15.3 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梬hile 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 resources you own.

  • Don't reference any other objects.

  • Don't throw any unhandled exceptions.

    [ Team LiB ] Previous Section Next Section