如何识别GC终结器线程?线程、如何识别、GC

2023-09-03 16:22:28 作者:据说地球没我不转

我有一个.net(C#)多线程应用程序,我想知道是否有一定的方法终结器线程内运行。

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

我已经使用Thread.CurrentThread.Name尝试,但它不工作(返回null)。

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?

推荐答案

确定一个主题,最好的方法就是通过其管理的ID:

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

Thread.CurrentThread.ManagedThreadId;

由于终结始终运行在GC的线程,你可以创建一个终结,将节省的线程ID(或线程对象)的静态valiable。

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.

示例:

public class ThreadTest {
    public static Thread GCThread;

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

在你的code只是创建这个类的一个实例,并做了垃圾收集:

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);
}
 
精彩推荐
图片推荐