关于这个问题,之前网上看到要自己计算,那种方法比较复杂。直接用C#的PerformanceCounter组件可以快捷的解决这个问题。但很纠结的是,我直接自己定义一个PerformanceCounter,拿不到数据。如下面 button2_Click
但在窗体上添加一个performanceCounter组件,组件属性里设置:CategoryName = "Process",CounterName = "% Processor Time",InstanceName = "Idle",这样就能取得CPU的使用率了。
private void button1_Click(object sender, EventArgs e)
{
string str = performanceCounter1.NextValue().ToString();
MessageBox.Show(str);
} private void button2_Click(object sender, EventArgs e)
{
PerformanceCounter myProcessCounter = new PerformanceCounter();
myProcessCounter.CategoryName = "Process";
myProcessCounter.CounterName = "% Processor Time";
myProcessCounter.InstanceName = "Idle";
string cpuLoad = myProcessCounter.NextValue().ToString();
MessageBox.Show(cpuLoad);
}
目前想不明白为什么会这样。目前自己写的程序里,用了直接在窗体上添加组件的方法,InstanceName从Process的ProcessName过来。
另外还有个问题,为什么,这里获取的第一次的CPU使用率是0。
但在窗体上添加一个performanceCounter组件,组件属性里设置:CategoryName = "Process",CounterName = "% Processor Time",InstanceName = "Idle",这样就能取得CPU的使用率了。
private void button1_Click(object sender, EventArgs e)
{
string str = performanceCounter1.NextValue().ToString();
MessageBox.Show(str);
} private void button2_Click(object sender, EventArgs e)
{
PerformanceCounter myProcessCounter = new PerformanceCounter();
myProcessCounter.CategoryName = "Process";
myProcessCounter.CounterName = "% Processor Time";
myProcessCounter.InstanceName = "Idle";
string cpuLoad = myProcessCounter.NextValue().ToString();
MessageBox.Show(cpuLoad);
}
目前想不明白为什么会这样。目前自己写的程序里,用了直接在窗体上添加组件的方法,InstanceName从Process的ProcessName过来。
另外还有个问题,为什么,这里获取的第一次的CPU使用率是0。
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货