如何识别GC Finalizer线程?
我有一个 .NET (C#) 多线程应用程序,我想知道某个方法是否在 Finalizer 线程内运行。
我尝试过使用 Thread.CurrentThread.Name 但它不起作用(返回 null)。
有人知道如何查询当前线程以发现它是否是 Finalizer 线程?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
识别线程的最佳方法是通过其托管 id:
由于终结器始终在 GC 线程中运行,因此您可以创建一个终结器,将线程 id(或线程对象)保存在静态变量中。
示例:
在您的代码中只需创建此类的实例并执行垃圾收集:
The best way to identify a thread is through its managed id:
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:
in your code just create an instance of this class and do a garbage collection:
如果可以选择调试,您可以使用 WinDbg + SoS.dll 轻松找到它。
!threads
命令显示应用程序中的所有托管线程,并且终结器线程通过注释专门突出显示。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 的代码还可以稍微改进一下......
Y Low's code could be improved slightly...
我认为即使使用调试 API 也是不可能的,请参阅 此博客文章了解更多信息。
I don't think that is possible even using the debugging APIs, see this blog post for more info.