C#测量特定应用程序的带宽

时间:2018-10-08 11:39:38

标签: c# performancecounter system.diagnostics

我需要测量我制作的应用程序的带宽。假设此应用程序名为std::abs

我制作了一个名为myapp.exe(BM)的库,该库是从BandwidthMonitor内部调用的。 myapp.exe定期调用myapp.exe并返回BM.Measure()

我的BandwidthMeasurement如下:

BM

由于某些原因,public class BandwidthMonitor { PerformanceCounter bandwidthCounter; PerformanceCounter dataReceivedCounter; PerformanceCounter dataSentCounter; List<float> byetsSent = new List<float>(); List<float> byetsReceived = new List<float>(); List<float> byetsUtilization = new List<float>(); float bandwidth; int ticks = 0; static string categoryName = ".NET CLR Networking 4.0.0.0"; public BandwidthMonitor() { try { bandwidthCounter = new PerformanceCounter(); bandwidthCounter.CategoryName = categoryName; bandwidthCounter.CounterName = "Current Bandwidth"; bandwidthCounter.InstanceName = instance; bandwidthCounter.ReadOnly = true; dataReceivedCounter = new PerformanceCounter(); dataReceivedCounter.CategoryName = categoryName; dataReceivedCounter.CounterName = "Bytes Received/sec"; dataReceivedCounter.InstanceName = instance; dataReceivedCounter.ReadOnly = true; dataSentCounter = new PerformanceCounter(); dataSentCounter.CategoryName = categoryName; dataSentCounter.CounterName = "Bytes Sent/sec"; dataSentCounter.InstanceName = instance; dataSentCounter.ReadOnly = true; Console.WriteLine("Bandwidth monitor ready."); } catch (Exception ex) { Console.WriteLine(ex); } } public BandwidthMeasurement Measure() { var measurement = new BandwidthMeasurement(); ticks++; try { var bytesSent = dataSentCounter.RawValue; var bytesReceived = dataReceivedCounter.RawValue; measurement.BytesSent = bytesSent; measurement.ByesReceived = bytesReceived; double utilization = (8 * (bytesSent + bytesReceived)) / (bandwidth * ticks) * 100; measurement.Utilization = utilization; } catch (Exception ex) { Console.WriteLine(ex); } return measurement; } //https://stackoverflow.com/a/27418721/596841 private static string GetInstanceName() { string returnvalue = "not found"; //Checks bandwidth usage for CUPC.exe..Change it with your application Name string applicationName = "myapp"; PerformanceCounterCategory[] Array = PerformanceCounterCategory.GetCategories(); for (int i = 0; i < Array.Length; i++) { if (Array[i].CategoryName.Contains(categoryName)) foreach (var item in Array[i].GetInstanceNames()) { Console.WriteLine(item); if (item.ToLower().Contains(applicationName.ToString().ToLower())) returnvalue = item; } } return returnvalue; } } 总是返回GetInstanceName()。我不知道为什么。

我已经尝试过:

  • not found设置为categoryName
  • .NET CLR Networking myapp传递到processId并查找类别。
  • 延迟BM的实例化点,以确保BM完全加载并首先运行(我认为这毫无意义,但是我不知道可以尝试什么...在这里抓稻草!)。
myapp

传递processId也找不到实例名称。

我不断收到异常:

  

无法找到具有指定类别名称“ .NET CLR Networking 4.0.0.0”的性能计数器。

我在做什么错了?

0 个答案:

没有答案