Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify the GC Finalizer thread?

I have a .NET (C#) multi-threaded application and I want to know if a certain method runs inside the Finalizer thread.

I've tried using Thread.CurrentThread.Name but it doesn't work (returns null).

Anyone knows how can I query the current thread to discover if it's the Finalizer thread?

like image 709
Dror Helper Avatar asked Nov 25 '08 18:11

Dror Helper


People also ask

What is a Finalizer thread?

Finalizer thread picks up objects from this queue - runs finalize - and releases the object. If this thread will be deadlocked the ReferenceQueue Queue will grow up and at some point OOM error will become inexorable. Also the resources will be hogged up by the objects in this queue.

What is finalizer thread in C#?

The finalizer thread is a specialized thread that the Common Language Runtime (CLR) creates in every process that is running . NET code. It is responsible to run the Finalize method (for the sake of simplicity, at this point, think of the finalize method as some kind of a destructor) for objects that implement it.


2 Answers

The best way to identify a thread is through its managed id:

Thread.CurrentThread.ManagedThreadId;

Since a finalizer always runs in the GC's thread you can create a finalizer that will save the thread id (or the thread object) in a static valiable.

Sample:

public class ThreadTest {
    public static Thread GCThread;

    ~ThreadTest() {
        ThreadTest.GCThread = Thread.CurrentThread;
    }
}

in your code just create an instance of this class and do a garbage collection:

public static void Main() {
    ThreadTest test = new ThreadTest();
    test = null;
    GC.Collect();
    GC.WaitForPendingFinalizers();

    Console.WriteLine(ThreadTest.GCThread.ManagedThreadID);
}
like image 161
Yona Avatar answered Sep 19 '22 20:09

Yona


If debugging is an option you can easily find it using WinDbg + SoS.dll. The !threads command displays all managed threads in the application and the finalizer thread is specifically highlighted with a comment.

like image 43
Brian Rasmussen Avatar answered Sep 17 '22 20:09

Brian Rasmussen