我需要测量我制作的应用程序的带宽。假设此应用程序名为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”的性能计数器。
我在做什么错了?