开发者

detect when a new managed thread has been created

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

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.

EDIT: Using Process.GetCurrentProcess(). Threads is not OK as the CLR does not guar开发者_高级运维antee 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.

See How can I enumerate all managed threads in C#?

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.


A solution could be to store your threads in a Queue when you create them and check regularly the content of the Queue. Not a perfect solution though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜