Search code examples
c#garbage-collectionfinalizer

Does an object with a pending finalizer need to be collected by the GC more than one time?


I am reading the "Disposal and Garbage Collection" chapter of book C# 8.0 in a Nutshell. When it comes to finalizers, it says:

The GC identifies the unused objects for deletion, those without finalizers are deleted immediately, those with pending finalizers are kept alive and are put onto a special queue. When the garbage collection is complete and your program continues executing, the finalizer thread then starts running in parallel to the program, picking objects off that special queue and running their finalization methods.

Does this paragraph mean that an object waiting for finalization need to be collected by the GC again? I assumed it already been detected as garbage by GC, why does it need to be collected after finalization again?


Solution

  • Well, the objects were not 'collected' the first time. They were seen to need additional processing (finalizer code needs to run) and put on the finalization queue so they could be processed separately. This ends up putting them on the 'freachable' queue, which has now resurrected the object: it is now referenced by the freachable queue and is no longer eligible for collection. It will be unreachable after the finalizer actually executes and the object is removed from the freachable queue.

    (This is how it used to work, not sure if things have changed in newer .NET versions, but I'm not aware of any.)

    So the object is not really 'collected' more than once, if by 'collected' we understand that the memory was reclaimed. It does, however, need additional processing and will be re-evaluated by the GC again at a later point in time.