獲得獲得InvalidOperationException異常:在System.dll中使用時PerformanceCounters
'System.InvalidOperationException' 的附加信息:
拋出異常
類別不存在。
代碼:每
.nextValue();
我曾嘗試在
CategoryName
加入Processor Information
,但也沒有幫助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(); } } }
得到錯誤。
編輯: @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