2016-01-19 33 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