Jimmy Habanero
Jimmy Habanero

Reputation: 35

performance monitor - getting current downloaded bytes

I need to monitor all internet traffic and collect how many bytes was downloaded.

Im trying to use performance counter but it doesnt get the current value, instead it shows only 0. It works when i'm using previously set instance name, but when i'm trying to iterate all of them the value doesnt update

static PerformanceCounterCategory category = new PerformanceCounterCategory("Network Interface");
String[] instances = category.GetInstanceNames();        
double bytes;       

private void updateCounter()
{
    foreach (string name in instances)
    {
        PerformanceCounter bandwitchCounter = new PerformanceCounter("Network Interface", "Bytes Received/sec", name);

        bytes += bandwitchCounter.NextValue();
        textBox1.Text = bytes.ToString();
    }   
}

now when i set the timer off, the instance name changes but not the value

Upvotes: 1

Views: 1209

Answers (2)

Jimmy Habanero
Jimmy Habanero

Reputation: 35

I'll answer myself. as OldFart mentioned, by calling new object each time I reset the counter to 0 every time. I managed to handle this by previously creating a list of all instances and iterating them later. Like this:

List<PerformanceCounter> instancesList = new List<PerformanceCounter>();
private void InitializeCounter(string[] instances)
{

    foreach(string name in instances)
    {
        instancesList.Add(new PerformanceCounter("Network Interface", "Bytes Received/sec", name));
    }

}
private void updateCounter()
{
    foreach(PerformanceCounter counter in instancesList)
    {
        bytes += Math.Round(counter.NextValue() / 1024, 2);
        textBox1.Text = bytes.ToString();
    }
}

Upvotes: 1

OldFart
OldFart

Reputation: 2479

This is a rate counter. The first time you read a rate counter (by calling NextValue), it returns 0. Subsequent reads will calculate the rate since the last time you called NextValue.

Since you create a new PerformanceCounter object each time, NextValue will always return 0.

You might be able to get the information you want by looking at RawValue instead.

Upvotes: 3

Related Questions