如何识别GC终结器线程? [英] How to identify the GC Finalizer thread?

查看:162
本文介绍了如何识别GC终结器线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.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);
}

这篇关于如何识别GC终结器线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆