Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to count managed threads in my AppDomain?

Is there a way to find out how many managed thread I use (including ThreadPool)?

When I get count of unmanaged threads through GetProcess I have an insane number of it (21 at very beginning)

like image 316
Boppity Bop Avatar asked Jun 18 '10 10:06

Boppity Bop


2 Answers

That's not the way it works. Any thread in a managed program can execute managed code, including ones that were originally started as an unmanaged thread. Which most are, the main thread and any threadpool thread starts life executing purely unmanaged code. It thunks into managed code though the kind of gateway provided by Marshal.GetDelegateForFunctionPointer().

Seeing dozens of (otherwise inactive) threads is not unusual. They typically are threadpool threads and threads started by COM servers. .NET is missing the plumbing you'd need to use Thread.ManagedThreadId on those threads. That's intentional, a logical .NET thread doesn't have to be a physical operating system thread. Although there's no host in current use where that's not the case.

You will have to avoid having to ask the question.

like image 167
Hans Passant Avatar answered Sep 22 '22 23:09

Hans Passant


I have not checked whether it is possible using the debugging interfaces but since VS displays managed threads in its debugger, you should be able to get them in yours too.

In .NET, writing a debugger is much easier than you may expect. Implementing the debugger basically consists of implementing the ICorDebug interface.

There is a sample from Microsoft: Managed Debugger Sample

like image 42
Marek Avatar answered Sep 21 '22 23:09

Marek