How to count the amount of concurrent threads in .NET application? How to count the amount of concurrent threads in .NET application? multithreading multithreading

How to count the amount of concurrent threads in .NET application?


There are different kinds of threads, I think. The operating system's threads for the application you're running, can be counted with:

int number = Process.GetCurrentProcess().Threads.Count;

It seems to count System.Diagnostics.ProcessThread instances. Maybe you need to count another kind of thread, like "managed threads", so I'm not sure my answer is what you seek.


I'm not a specialist but I can imagine that the threads can be re used while its activity swapped somewhere.

No - apart from some very specific cases (which you almost certainly don't need to worry about) threads aren't use reentrantly. The thread will be reused to run another iteration (or some other task) after the current iteration has completed, but it won't be asked to do something else while your code is running.

So your current approach is reasonable, basically.

Anyway, how to directly count the amount of running threads in .NET?

You can look in perfmon, which will graph it for you. (If the process is under your control, it's simplest to start the process but make it wait for input, then open up perfmon, add a counter from the "Process" options, select "Thread Count" as the counter to add, and restrict it to the process you're interested in from the dropdown. Hit OK, and then make your process start working.)

EDIT: To answer the update:

That is, the number of threads are not ever decreasing telling that the cited above method is incorrect

No, all it shows is that the number of threads actively running your code decreases, but the threads are kept around. That's entirely natural for a thread pool.

why cannot ProcessThread be used?

You're simply using it inappropriately. Jeppe said that the system was counting the instances of ProcessThread whereas your code tries to assign a class to a variable:

diagThreadCount=System.Diagnostics.ProcessThread

That's simply invalid code. The error message shows that the compiler realizes it's the name of a type, but you can't just assign a type name to a variable.