Получение:Получение InvalidOperationException при использовании PerformanceCounters
Exception брошенную: '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
, но не помогает.
EDIT: @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();
}
}
}
Не могли бы вы по крайней мере дать нам трассировку стека и объяснить немного, что ты пытаясь сделать? – Fourat