Wednesday 6 January 2010

PerformanceCounter c#

OK, after the last try to find some intresting data with the PerformanceCounter, i wanted to see what other counter it has, so i made a program to show me all the option, or at least the ones that are easy to find out, so i came up with this program:

Unlike the previous programs, this one is not a simple "throw everthing at the poor label", you will need:
-3 listboxs, each with a ListBox1SelectedIndexChanged(object sender, EventArgs e) event.
-and of course, one label to "throw everthing at"
Should look like this if you want:














Now, for the much more intresting code(not all that intersting, but the data you can get from the code is) :


void MainFormLoad(object sender, EventArgs e)
{
foreach (PerformanceCounterCategory pcc in PerformanceCounterCategory.GetCategories())
listBox1.Items.Add(pcc.CategoryName);
}

void ListBox1SelectedIndexChanged(object sender, EventArgs e)
{
int flag=1;
listBox2.Items.Clear();
listBox3.Items.Clear();
PerformanceCounterCategory pcc=new PerformanceCounterCategory(listBox1.SelectedItem.ToString());
foreach (string insname in pcc.GetInstanceNames())
{
flag=0;
listBox2.Items.Add(insname);
}
if (flag==1)
{
foreach (PerformanceCounter pc in pcc.GetCounters())
{
listBox3.Items.Add(pc.CounterName);
}
}
}

void ListBox2SelectedIndexChanged(object sender, EventArgs e)
{
listBox3.Items.Clear();
if (listBox2.SelectedItem==null) return;
PerformanceCounterCategory pcc=new PerformanceCounterCategory(listBox1.SelectedItem.ToString());
try{
foreach (PerformanceCounter pc in pcc.GetCounters(listBox2.SelectedItem.ToString()))
{
listBox3.Items.Add(pc.CounterName);
}
}
catch {label1.Text="instance invalid";}
}

void ListBox3SelectedIndexChanged(object sender, EventArgs e)
{
try{
PerformanceCounter pc;
if (listBox2.SelectedItem==null)
pc=new PerformanceCounter(listBox1.SelectedItem.ToString(),listBox3.SelectedItem.ToString());
else
pc=new PerformanceCounter(listBox1.SelectedItem.ToString(),
listBox3.SelectedItem.ToString(),listBox2.SelectedItem.ToString());
pc.NextValue();//for some, the first is always 0
label1.Text=pc.NextValue().ToString();
if ((label1.Text=="0")||(label1.Text=="100"))
{
float activity = 0;
int NormalDegree = 20;
for (int i = 0; i < NormalDegree; i++)
{
activity += pc.NextValue();
Application.DoEvents();
System.Threading.Thread.Sleep(20);
}
label1.Text=(activity/NormalDegree).ToString("g3");
if (listBox3.SelectedItem.ToString().StartsWith("%")) label1.Text+="%";
}
}
catch
{
label1.Text="counter invalid";
}
}

No comments:

Post a Comment