我想在c#中获得一个应用程序的总的CPU使用情况。我已经找到了很多方法来深入研究进程的属性,但我只想知道进程的CPU使用情况,以及你在TaskManager中得到的总CPU。
我怎么做呢?
我想在c#中获得一个应用程序的总的CPU使用情况。我已经找到了很多方法来深入研究进程的属性,但我只想知道进程的CPU使用情况,以及你在TaskManager中得到的总CPU。
我怎么做呢?
当前回答
没事的,我知道了!谢谢你的帮助!
下面是代码:
private void button1_Click(object sender, EventArgs e)
{
selectedServer = "JS000943";
listBox1.Items.Add(GetProcessorIdleTime(selectedServer).ToString());
}
private static int GetProcessorIdleTime(string selectedServer)
{
try
{
var searcher = new
ManagementObjectSearcher
(@"\\"+ selectedServer +@"\root\CIMV2",
"SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor WHERE Name=\"_Total\"");
ManagementObjectCollection collection = searcher.Get();
ManagementObject queryObj = collection.Cast<ManagementObject>().First();
return Convert.ToInt32(queryObj["PercentIdleTime"]);
}
catch (ManagementException e)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}
return -1;
}
其他回答
对于那些仍然无法获得与任务管理器匹配的CPU使用总数的人,您应该使用以下语句:
new PerformanceCounter("Processor Information", "% Processor Utility", "_Total");
您可以使用WMI获取CPU百分比信息。如果您拥有正确的权限,您甚至可以登录到远程计算机。看看http://www.csharphelp.com/archives2/archive334.html,了解一下你能完成什么。
Win32_Process名称空间的MSDN引用可能也有帮助。
另见CodeProject示例如何:(几乎)一切在WMI通过c#。
在花了一些时间阅读了几个看起来相当复杂的不同线程后,我想到了这个。我需要它为一个8核的机器,我想监视SQL server。对于下面的代码,我将“sqlservr”作为appName传入。
private static void RunTest(string appName)
{
bool done = false;
PerformanceCounter total_cpu = new PerformanceCounter("Process", "% Processor Time", "_Total");
PerformanceCounter process_cpu = new PerformanceCounter("Process", "% Processor Time", appName);
while (!done)
{
float t = total_cpu.NextValue();
float p = process_cpu.NextValue();
Console.WriteLine(String.Format("_Total = {0} App = {1} {2}%\n", t, p, p / t * 100));
System.Threading.Thread.Sleep(1000);
}
}
它似乎正确地测量了我的8核服务器上SQL所使用的CPU百分比。
public int GetCpuUsage()
{
var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", Environment.MachineName);
cpuCounter.NextValue();
System.Threading.Thread.Sleep(1000); //This avoid that answer always 0
return (int)cpuCounter.NextValue();
}
原始信息在此链接https://gavindraper.com/2011/03/01/retrieving-accurate-cpu-usage-in-c/
这似乎对我有用,一个等待处理器达到一定百分比的例子
var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
int usage = (int) cpuCounter.NextValue();
while (usage == 0 || usage > 80)
{
Thread.Sleep(250);
usage = (int)cpuCounter.NextValue();
}