问题
I'm trying to display the received bytes per second and have them displayed in the console once a second. The I am presented with a Invalid Operation Exception once it reaches .nextvalue.
PerformanceCounter NetworkDownSpeed = new PerformanceCounter("Network Interface", "Bytes Received/sec");
float CurrentNetworkDownSpeed = (int)NetworkDownSpeed.NextValue();
while (true)
{
Console.WriteLine("Current Network Download Speed: {0}MB", CurrentNetworkDownSpeed);
Thread.Sleep(1000);
}
回答1:
Sorry for answering after someone already did, but does this helps by any chance ?
private static void ShowNetworkTraffic()
{
PerformanceCounterCategory performanceCounterCategory = new PerformanceCounterCategory("Network Interface");
string instance = performanceCounterCategory.GetInstanceNames()[0]; // 1st NIC !
PerformanceCounter performanceCounterSent = new PerformanceCounter("Network Interface", "Bytes Sent/sec", instance);
PerformanceCounter performanceCounterReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", instance);
for (int i = 0; i < 10; i++)
{
Console.WriteLine("bytes sent: {0}k\tbytes received: {1}k", performanceCounterSent.NextValue() / 1024, performanceCounterReceived.NextValue() / 1024);
Thread.Sleep(500);
}
}
From here.
回答2:
NetworkDownSpeed.NextValue() can throw InvalidOperationException.
In NetworkDownSpeed.NextValue there is a comment that details the why.
// If the category does not exist, create the category and exit.
// Performance counters should not be created and immediately used.
// There is a latency time to enable the counters, they should be created
// prior to executing the application that uses the counters.
// Execute this sample a second time to use the category.
An alternative solution that takes care of this issue can be found on this stack overflow post.
来源:https://stackoverflow.com/questions/32211577/how-to-display-bytes-received-per-second-in-c-sharp