8

I have a program which calls a C++ library. The program processes has a large number of threads (50 - 60). Most of them seem to be created in C++ and I suspect most are suspended/waiting.

How do I find how many of these threads are active at a given point in time?

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
DayOne
  • 1,027
  • 1
  • 11
  • 16

2 Answers2

15

To actually determine the count of active threads, it's necessary to check the ThreadState property of each thread.

((IEnumerable)System.Diagnostics.Process.GetCurrentProcess().Threads)
    .OfType<System.Diagnostics.ProcessThread>()
    .Where(t => t.ThreadState == System.Diagnostics.ThreadState.Running)
    .Count();
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Nathan
  • 1,675
  • 17
  • 25
  • Looks like you might need to check your `using`s. `IEnumerable` requires `using System.Collections`, which isn't always included by default. `OfType` returns `IEnumerable` from `IEnumerable`. So you wouldn't need that if you're starting out with `IEnumerable` like you are. On first glance, your code looks like it works the same. – Nathan Jul 23 '14 at 19:23
  • This looks like java code, not c++ – Aleksandr Jun 21 '22 at 00:01
4

You could use Process Explorer to inspect threads. It will tell you in realtime how much CPU each is consuming, and can give you individual stack traces, which will indicate what they are blocked on.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365