如何在C#(托管代码)中获得*THREAD*的CPU使用率和/或RAM使用率?

Tim*_*uri 13 c# performance multithreading memory-management cpu-usage

我知道如何获得进程的CPU使用率和内存使用率,但我想知道如何在每个线程级别上获取它.如果最好的解决方案是做一些P-Invoking,那也没关系.

我需要的例子:

Thread myThread = Thread.CurrentThread;

// some time later in some other function...

Console.WriteLine(GetThreadSpecificCpuUsage(myThread));
Run Code Online (Sandbox Code Playgroud)

jer*_*jvl 10

如上所述,内存使用无法回答,因为这是整个过程的一个属性,但CPU使用:

Process p = Process.GetCurrentProcess(); // getting current running process of the app
foreach (ProcessThread pt in p.Threads)
{
    // use pt.Id / pt.TotalProcessorTime / pt.UserProcessorTime / pt.PrivilegedProcessorTime
}
Run Code Online (Sandbox Code Playgroud)


eri*_*len 7

您无法获得每个线程的内存使用量,因为内存在进程中的所有线程之间共享.操作系统如何知道您是否在一个线程中分配了内存并在另一个线程中使用了它.这意味着什么?


Tet*_*ron 3

这是一个执行您想要的操作的示例 http://www.codeproject.com/KB/system/processescpuusage.aspx