How to identify the GC Finalizer thread?

扶醉桌前 提交于 2019-12-05 05:46:22

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);
}

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.

Y Low's code could be improved slightly...

public static void Main()
{
  ThreadTest test = new ThreadTest();
  test = null;

  GC.Collect();
  GC.WaitForPendingFinalizers();

  Console.WriteLine(ThreadTest.GCThread.ManagedThreadID);
}

I don't think that is possible even using the debugging APIs, see this blog post for more info.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!