使用PerformanceCounters时获取InvalidOperationException

时间:2016-11-13 11:46:55

标签: c# performancecounter

获得:

  

抛出异常:' System.InvalidOperationException'在System.dll

其他信息:

  

类别不存在。

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
    PerformanceCounter cpuCounter;
    PerformanceCounter ramCounter;
    public Form1()
    {
        InitializeComponent();
    }
    int timeX = 0;
    private void timer1_Tick(object sender, EventArgs e)
    {
        cpuCounter = new PerformanceCounter();
        cpuCounter.CategoryName = "Processor";
        cpuCounter.CounterName = "% Processor Time";
        cpuCounter.InstanceName = "_Total";


        float cpuUsage = 0.00F;
        cpuCounter.NextValue();
        cpuUsage = cpuCounter.NextValue();
        textBox1.Text = cpuUsage.ToString();


        ramCounter = new PerformanceCounter("Memory", "Available MBytes");
        float ram = ramCounter.NextValue();
        textBox2.Text = ram.ToString();

        chart1.Series["CPU Usage"].Points.AddXY(timeX, (int)cpuUsage);
        chart2.Series["Memory Use"].Points.AddXY(timeX, (int)ram);

    }

    private void button1_Click(object sender, EventArgs e)
    {
       timer1.Start();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        timer1.Stop();
    }
}
}

每个.nextValue();

都会出错

我尝试在Processor Information中添加CategoryName,但也没有帮助。

编辑: @Jim这是我做出更改后的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
namespace WindowsFormsApplication12
{
public partial class Form1 : Form
{
    PerformanceCounter cpuCounter;
    PerformanceCounter ramCounter;

    public Form1()
    {
        InitializeComponent();

        InitializeCounters();
    }

    private void InitializeCounters()
    {
        cpuCounter = new PerformanceCounter();
        cpuCounter.CategoryName = "Processor";
        cpuCounter.CounterName = "% Processor Time";
        cpuCounter.InstanceName = "_Total";

       // ramCounter = new PerformanceCounter("Memory", "Available MBytes");
    }

    int timeX = 0;
    private void timer1_Tick(object sender, EventArgs e)
    {
        float cpuUsage = 0.00F;
        cpuUsage = cpuCounter.NextValue();
        textBox1.Text = cpuUsage.ToString();

        float ram = ramCounter.NextValue();
        textBox2.Text = ram.ToString();

        // Your chart stuff
        //chart1.Series["CPU Usage"].Points.AddXY(timeX, (int)cpuUsage);
        //chart2.Series["Memory Use"].Points.AddXY(timeX, (int)ram);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        timer1.Start();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        timer1.Stop();
    }
}

}

2 个答案:

答案 0 :(得分:2)

每次计时器滴答时,您都在创建新的效果计数器,只需初始化计数器一次

Form1代码背后

PerformanceCounter cpuCounter;   
PerformanceCounter ramCounter;

public Form1()
{
    InitializeComponent();

    InitializeCounters();
}

private void InitializeCounters()
{
    cpuCounter = new PerformanceCounter();
    cpuCounter.CategoryName = "Processor";
    cpuCounter.CounterName = "% Processor Time";
    cpuCounter.InstanceName = "_Total";

    ramCounter = new PerformanceCounter("Memory", "Available MBytes");
}

int timeX = 0;
private void timer1_Tick(object sender, EventArgs e)
{        
    float cpuUsage = 0.00F;
    cpuUsage = cpuCounter.NextValue();
    textBox1.Text = cpuUsage.ToString();

    float ram = ramCounter.NextValue();
    textBox2.Text = ram.ToString();

    // Your chart stuff
    //chart1.Series["CPU Usage"].Points.AddXY(timeX, (int)cpuUsage);
    //chart2.Series["Memory Use"].Points.AddXY(timeX, (int)ram);
}

private void button1_Click(object sender, EventArgs e)
{
    timer1.Start();
}

private void button2_Click(object sender, EventArgs e)
{
    timer1.Stop();
}

旁注:

当不再使用它们时,Dispose计数器。也许在Form Closing事件上。

cpuCounter.Dispose();
ramCounter.Dispose();

结果

enter image description here

错误案例

如果我的示例仍然抛出错误,这很可能是因为系统上的一个或多个性能计数器已损坏。

重建所有效果计数器:

  • 打开命令提示符(具有管理员权限)
  • 运行命令:lodctr /R

消息:

  

信息:成功重建性能计数器设置......

将成功出现。

如果您收到消息:

  

无法从系统备份存储重建性能计数器设置,错误代码为2

可能的解决方案:

  • 关闭所有正在运行的程序
  • 确保使用lodctr /R大写R
  • 如果在目录system32中移动到目录SysWOW64(使用cd ..> cd syswow64)并重试此目录中的lodctr /R命令

答案 1 :(得分:0)

在使用PerformanceCounter之前创建一个类别。 msdn

中的更多详细信息和示例
    const String categoryName = "Processor";
    const String counterName = "% Processor Time";

    if ( !PerformanceCounterCategory.Exists(categoryName) ) 
    {

        CounterCreationDataCollection CCDC = new CounterCreationDataCollection();

        // Add the counter.
        CounterCreationData ETimeData = new CounterCreationData();
        ETimeData.CounterType = PerformanceCounterType.ElapsedTime;
        ETimeData.CounterName = counterName;
        CCDC.Add(ETimeData);       

        // Create the category.
        PerformanceCounterCategory.Create(categoryName,
                "Demonstrates ElapsedTime performance counter usage.",
            PerformanceCounterCategoryType.SingleInstance, CCDC);
    }