gpt4 book ai didi

c# - 使用 PerformanceCounters 时出现 InvalidOperationException

转载 作者:行者123 更新时间:2023-11-30 12:22:34 26 4
gpt4 key购买 nike

<分区>

获得:

Exception thrown: 'System.InvalidOperationException' in System.dll

附加信息:

Category does not exist.

代码:

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(); 上获取错误

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

编辑:@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();
}
}

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com