2016-01-19 68 views
1

我正在尝试使用C#PerformanceCounter类来返回系统度量标准。收到的字节总是返回0

// 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(

以上在这个意义上的作品,它并不会抛出异常,但总是返回0

我曾经尝试都NextSampleNextValue具有相同结果的最后一行。如果我将InstanceName更改为进程名称,我再次获得相同的结果。如果InstanceName设置为其他任何内容,则在拨打RawValue时引发异常Instance 'XYZ' does not exist in the specified Category.

任何想法?

+0

使用嗅探器如fiddler或wireshark来验证数据是通过网络发送/接收的。 – jdweng

+0

@AlainD:如果您正在收集系统级指标,请查看[Statsify](https://bitbucket.org/aeroclub-it/statsify)是否符合您的需求。 –

+0

@jdweng:由于我使用Windows套接字连接到各种服务器,因此肯定会发送/接收数据。我可以计算手动发送和接收的字节数(并且它们不为零)。问题的结果是,按照Anton的回答,必须特别启用.NET网络性能计数器。 – AlainD

回答

1

根据Networking Performance Counters

网络性能计数器需要在配置文件中启用使用。

如果启用了联网计数器,则会创建并更新每个AppDomain和全局性能计数器。如果禁用,应用程序将不会提供任何网络性能计数器数据。

+0

工作!但不是没有一点麻烦。如果所需的'条目放置在app.config文件的顶部,则网络将完全停止以供我的应用程序使用(无法再通过套接字连接)。我在app.config中有一个SQLEXPRESS连接字符串。通过在app.config的底部放置'部分,进程开始返回接收和发送的字节!谢谢。 – AlainD