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

时间:2016-06-13 14:57:13

标签: c# .net performancecounter

鉴于以下代码,我可以得到给定进程的活动线程总数:

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返回的号码。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

Process.Threads将包括所有线程,包括本机OS线程。 .NET性能计数器只会返回托管线程。匹配Process.Threads的效果计数器为\\Process(myProcess)\Thread Count