How to identify the GC Finalizer thread?
Asked Answered
F

4

7

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?

Fixture answered 25/11, 2008 at 18:46 Comment(5)
Why do you need to know which thread is running GC?Absonant
my fuction runs code that I do not want to run during finalizationFixture
Besides does it really matters? There is a problem I want to find how to solve.Fixture
You should never be offended when someone asks "why do you want to do that" in response to a question; often, they've spotted a pattern and they're trying to determine whether or not they can suggest a cleaner solution to your actual problem. Obviously, this can sometimes irk you if you [cont'd]Killen
know what you're doing, but you shouldn't feel as if they're questioning your judgement.Killen
C
14

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);
}
Chante answered 25/11, 2008 at 19:6 Comment(0)
A
3

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.

Arboretum answered 11/1, 2009 at 21:30 Comment(0)
C
1

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);
}
Cottrell answered 25/11, 2008 at 19:55 Comment(0)
S
0

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

Susysuter answered 25/11, 2008 at 19:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.