Why is it not recommended to serialize an object in its finalizer?

In Headfirst C #, I get the point of view that โ€œitโ€™s not practical to serialize an object in your finalizer, because serialization requires the whole tree of objects to be on the heap, but in the end you can lose a vital part of your program because some objects could be assembled before the finalizer starts. "

My question is, since my object receives a link to others (this means that there is at least one link to other objects), how can they be garbage collected before my finalizer works?

+5
source share
2 answers

The problem with finalizers is that they provide very few guarantees:

  • they are never guaranteed to ever run
  • you cannot predict when they will be executed
  • when they are executed, it is possible that some of the objects that they reference are already completed, so your object may not be in a valid state.

Eric Lippert has two great blog posts about this:

In any case, 99% of the classes you ever write probably shouldn't have a finalizer at all. There are very few cases when they are really necessary. If you need to perform a cleanup after you finish using the object, use IDisposable instead, which at least you can control in a deterministic way.

+8
source

Since the garbage collector does not determine the order in which finalizers are started and does not care about whether your objects are completed out of order.

By the time your finalizer finishes, the GC has already decided that it and every object that it refers to are not available, and therefore all of these child objects will also be assembled. Each of these objects is added to the finalizer queue, but there is no guarantee that the GC will process them in any reasonable order.

This is one of the limitations of what you can do in the finalizer: you must assume that all of your child objects could already be destroyed. The documentation for Object.Finalize calls this explicitly:

Finalizers of two objects are not guaranteed to run in any particular order, even if one object refers to another. That is, if object A has a reference to object B, and both have finalizers, object B may already be completed when the finalizer of object A begins.

+9
source

All Articles