检测何时创建了新的托管线程 [英] detect when a new managed thread has been created

查看:48
本文介绍了检测何时创建了新的托管线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道是否有可能检测到在托管环境中何时创建了新线程吗?

Does anyone know if it is possible to detect when a new thread has been created in a managed environment?

我想要一个应用程序中所有线程的列表(每个线程的ID和名称).我在Visual Studio中使用并发可视化器,它仅显示线程ID(不显示线程名称).如果您有20多个没有名称的线程,则很难可视化程序流程.

I would like to have a list of all threads in my application (id and name of each thread). I am using Concurrency Visualizer in Visual Studio and it only displays thread ids (not thread names). And it's quite difficult to visualize the program flow if you have 20+ threads without their names.

使用 Process.GetCurrentProcess().线程不正确,因为CLR无法保证托管线程和非托管线程之间的一对一映射.

Using Process.GetCurrentProcess(). Threads is not OK as the CLR does not guarantee one-to-one mapping between managed and unmanaged threads.

一种解决方案是创建某种线程管理器,通过该线程管理器必须完成所有线程的创建.它还将管理所有当前活动线程的列表.

One solution would be to create some sort of thread manager via which all thread creation would have to be done. It would also manage list of all currently alive threads.

推荐答案

答案是不能"-您甚至无法枚举所有当前的托管"线程,更不用说在创建/销毁线程时得到通知了.

The answer is no you can't - you can't even enumerate all current "managed" threads, let alone get notified when one is created / destroyed.

请参见如何枚举C#中的所有托管线程?

注意:您可以使用 Process 类枚举一个进程中的所有线程:

Note: You can enumerate all thread in a process using the Process class:

Process.GetCurrentProcess().Threads

但这不会告诉您其中哪些是托管的",并且不会在创建或销毁线程时通知您.

This doesn't tell you which of those is "managed" however, and doesn't notify you when a thread is created or destroyed.

您可能会尝试通过在托管跟踪的堆栈跟踪中查找哪些线程是托管"的,但是老实说,我不知道这是否真的适用于非托管线程,而且所有这些都开始真正地出现了.躲闪!

You possibly could try and figure out which of those threads are "managed" by looking throug the stack trace for managed threads, but I have honestly no idea if this would actually work for unmanaged threads and this is all starting to look really dodgey!

new StackTrace().GetFrame(someThread)

只是要澄清-您几乎可以肯定不应该做任何这件事,它只是一些背景.

Just to clarify - you almost certainly shouldn't be doing any of this, its just some background.

这篇关于检测何时创建了新的托管线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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