This is an extract from a msdn article. article can be found here
There is a special runtime thread dedicated to calling Finalize methods. When the freachable queue is empty (which is usually the case), this thread sleeps. But when entries appear, this thread wakes, removes each entry from the queue, and calls each object's Finalize method. Because of this, you should not execute any code in a Finalize method that makes any assumption about the thread that's executing the code. For example, avoid accessing thread local storage in the Finalize method.
This is a question that I have asked before and I was downvoted for the same saying that there is no dedicated thread for Finalizable objects and my souce of information is wrong. If what this article explain is true than I want to know why do CLR needs a special thread for calling Finalize method ?
There is nothing about what finalizers do that need the separate thread, however consider this:
However, a plausible naive solution would be to do the following:
This would probably be quite simple to implement. The GC operation has free access to all the data structures related to the heaps and is free to do anything it wants, because no other thread that accesses these things are running.
However, this would make the program have "quite long" pauses from time to time, and would be quite unacceptable in most applications.
So instead the team that works on the GC has opted for the solution of suspending for the smallest possible time, suspending only when needed (generation 0 and 1 collection) while leaving the application running while generation 2 is collected. This is more difficult. Note, this is assumptions on my part, I don't have access to the actual design documentation or any solid information about this. The assumptions are based on the official documentation.
So back to the finalizer thread. These objects are already "dead" and slated for collection, so in lieu of the above design decision, why bother one of the main threads doing application work with this? Since the GC is already doing things in the background, handling finalization of dead objects in the same way seems like a good decision.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With