我尝试使用C#PerformanceCounter类来返回系统指标。
// 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。
我已尝试使用相同的结果NextSample
和NextValue
。如果我将InstanceName
更改为进程名称,我将再次获得相同的结果。如果将InstanceName
设置为其他任何内容,则在致电Instance 'XYZ' does not exist in the specified Category.
时会引发异常RawValue
。
有什么想法吗?
答案 0 :(得分:1)
根据Networking Performance Counters:
需要在要使用的配置文件中启用网络性能计数器。
如果启用了网络计数器,则会创建并更新每个AppDomain和全局性能计数器。如果禁用,则应用程序将不提供任何网络性能计数器数据。