AlainD
AlainD

Reputation: 6597

Bytes Received always returning 0

I'm trying to use the C# PerformanceCounter class to return system metrics.

// Initialisation
// Threads (total threads for all processes)
PerformanceCounter performThreads = new System.Diagnostics.PerformanceCounter();
((ISupportInitialize)(performThreads)).BeginInit();
performThreads.CategoryName = "System";
performThreads.CounterName = "Threads";
((ISupportInitialize)(performThreads)).EndInit();

// Bytes received (cumulative total bytes received over all open socket connections)
private PerformanceCounter m_pcSys_BytesSent;
PerformanceCounter performBytesR = new System.Diagnostics.PerformanceCounter();
((ISupportInitialize)(performBytesR)).BeginInit();
performBytesR.CategoryName = ".NET CLR Networking";
performBytesR.CounterName = "Bytes Received";
performBytesR.InstanceName = "_global_";
((ISupportInitialize)(performBytesR)).EndInit();

// Later on ... periodically poll performance counters
long lThreads = performThreads.RawValue;    // Works!
long lBytesR = performBytesR.RawValue;      // Always returns 0 :o(

The last line above works in the sense that it does not throw an exception but always returns 0.

I have tried both NextSample and NextValue with the same result. If I change InstanceName to the process name I again get the same result. If InstanceName is set to anything else the exception Instance 'XYZ' does not exist in the specified Category. is thrown when I call RawValue.

Any ideas?

Upvotes: 1

Views: 387

Answers (1)

Anton Gogolev
Anton Gogolev

Reputation: 115731

According to Networking Performance Counters:

Networking performance counters need to be enabled in the configuration file to be used.

If networking counters are enabled, this will create and update both per-AppDomain and global performance counters. If disabled, the application will not provide any networking performance counter data.

Upvotes: 1

Related Questions