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?

Tall Jeff
  • 9,834
  • 7
  • 44
  • 61
Dror Helper
  • 30,292
  • 15
  • 80
  • 129
  • Why do you need to know which thread is running GC? – Lasse V. Karlsen Nov 25 '08 at 19:14
  • my fuction runs code that I do not want to run during finalization – Dror Helper Nov 25 '08 at 19:29
  • Besides does it really matters? There is a problem I want to find how to solve. – Dror Helper Nov 25 '08 at 19:31
  • 1
    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] – Rob Jan 11 '09 at 21:28
  • know what you're doing, but you shouldn't feel as if they're questioning your judgement. – Rob Jan 11 '09 at 21:29

4 Answers4

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);
}
Yona
  • 9,392
  • 4
  • 33
  • 42
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.

Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317
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);
}
JoshL
  • 1,706
  • 1
  • 12
  • 13
0

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

Carl Serrander
  • 346
  • 1
  • 7