如何使用性能计数器获取进程的 运行 个线程数?

How can I obtain the count of running threads for a process using Performance Counters?

给出下面的代码,我可以获得给定进程的活动线程总数:

using (var p = Process.GetCurrentProcess())
{
    Console.WriteLine(p.Threads.Count);     
}

我想使用 PerformanceCounters 来实现这一点并且到目前为止已经尝试过(参考:https://msdn.microsoft.com/en-us/library/w8f5kw2e(v=vs.110).aspx):

var category = ".NET CLR LocksAndThreads";
var counterOne = "# of current logical Threads";
var counterTwo = "# of current physical Threads";
var coutnerThree = "# of current recognized threads";
var counterFour = "# of total recognized Threads";

var perfCounter = new PerformanceCounter(
    category,
    counterOne,
    "myProcess") { ReadOnly = true };
Console.WriteLine("Thread count: ", perfCounter.NextValue());

我无法匹配 Process 返回的号码。非常感谢任何帮助。

Process.Threads 将包括所有线程,包括本机 OS 线程。 .NET 性能计数器仅用于 return 个托管线程。匹配 Process.Threads 的性能计数器将是 \Process(myProcess)\Thread Count