How can I enumerate all managed threads in C#?
Solution 1
Debuggers are often able to do things "normal" code can't. You'd probably find that you can do this if you use the profiling/debugging API, but I don't believe you can do it from "normal" .NET code.
Solution 2
This sounds like a duplicate of "How to enumerate threads in .NET using the Name property?" - If so, the short answer is "keep track of your own threads yourself" - i.e. in a List<Thread>
or similar.
Solution 3
Take a look at Managed Stack Explorer:
MSE works by quickly attaching to a process when a stack trace is requested and the detaching the second the stack trace has been retrieved. This way the interference in the normal operation of the process is minimized.
Unfortunately, this means it has to done by an external process.
A similar tool is StackDump, which uses MDbg to generate the dump.
Related videos on Youtube
Randy Stegbauer
I'm a software developer living in Canada. I work with .NET on a daily basis, but dabble in anything else I can get my hands on.
Updated on April 17, 2022Comments
-
Randy Stegbauer about 2 years
Is it possible to enumerate all managed threads in C#? Visual Studio seems to be able to do this when you hit a break point while debugging. In the "Threads" window it shows a list of all running threads, including managed names. Does anyone know how it does this?
-
Contango about 8 yearsSee an answer here: stackoverflow.com/questions/10315862/get-list-of-threads/…
-
Hosam Aly@Marc, I disagree. Maybe he's working on an IDE and wants to include debugging capabilities. "Keep track of your own threads" is not a valid answer in this case. The question could be marked as duplicate, but the "short answer" is not the best one.
-
-
Randy Stegbauer over 15 yearsThis is what I may end up doing, I was just hoping there was already something doing it for me. :)
-
CrazyCasta over 11 yearsI don't see how to do it from a debugger either. It appears that the thread ids given in the debugger are the Win32 ids rather than the managed thread ids.
-
Jon Skeet over 11 years@CrazyCasta: I'm not saying you can explicitly do it from a debugger. I'm saying that when the debugger does list all threads, it can use APIs which aren't available elsewhere. Even if it lists Win32 ids, it still shows managed thread names, doesn't it?
-
CrazyCasta over 11 yearsI see what appear to be managed names, however there's a few problems. 1. It could be that the managed code is just setting the name of the unmanaged thread. 2. As has been stated, there is no defined 1:1 correlation between unmanaged and managed threads. Each unmanaged thread could be switching between two managed threads. 3. I would guess that the debugger is just enumerating unmanaged threads.