我在这里关注答案:
并按照他说的执行了一切。我的显示器是这样初始化的:
netSentCounter.CategoryName = ".NET CLR Networking";
netSentCounter.CounterName = "Bytes Sent";
netSentCounter.InstanceName = Misc.GetInstanceName();
netSentCounter.ReadOnly = true;
我可以正确地看到Misc.GetInstanceName()
返回“MyProcessName [id]”。但是,我不断收到实例在指定类别中不存在的异常。
我的理解是,在您实际发送或接收之前,不会创建净发送/接收的类别。
我已经按照答案中的描述添加了 app.config,如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.net>
<settings>
<performanceCounters enabled="true" />
</settings>
</system.net>
</configuration>
为什么我仍然收到错误消息?
这是我的监控代码:
public static class Monitoring
{
private static PerformanceCounter netSentCounter = new PerformanceCounter();
//Static constructor
static Monitoring()
{
netSentCounter.CategoryName = ".NET CLR Networking";
netSentCounter.CounterName = "Bytes Sent";
netSentCounter.InstanceName = Misc.GetInstanceName();
netSentCounter.ReadOnly = true;
}
/// <summary>
/// Returns the amount of data sent from the current application in MB
/// </summary>
/// <returns></returns>
public static float getNetSent()
{
return (float)netSentCounter.NextValue() / 1048576; //Convert to from Bytes to MB
}
}
还有我的杂项课:
public static class Misc
{
//Returns an instance name
internal static string GetInstanceName()
{
// Used Reflector to find the correct formatting:
string assemblyName = GetAssemblyName();
if ((assemblyName == null) || (assemblyName.Length == 0))
{
assemblyName = AppDomain.CurrentDomain.FriendlyName;
}
StringBuilder builder = new StringBuilder(assemblyName);
for (int i = 0; i < builder.Length; i++)
{
switch (builder[i])
{
case '/':
case '\\':
case '#':
builder[i] = '_';
break;
case '(':
builder[i] = '[';
break;
case ')':
builder[i] = ']';
break;
}
}
return string.Format(CultureInfo.CurrentCulture,
"{0}[{1}]",
builder.ToString(),
Process.GetCurrentProcess().Id);
}
/// <summary>
/// Returns an assembly name
/// </summary>
/// <returns></returns>
internal static string GetAssemblyName()
{
string str = null;
Assembly entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly != null)
{
AssemblyName name = entryAssembly.GetName();
if (name != null)
{
str = name.Name;
}
}
return str;
}
}
编辑:我已经从 Windows 中打开了资源监视器以查看问题所在。尽管将 app.config 设置为这样做,但计数器并未启动。
这是我看到的(在我的应用程序发送网络活动之前和之后)
并且名称不是我的方法返回的名称。我的方法返回“SuperScraper [appId]”,而在资源中它被称为“Superscraper.vshost.exe”。
所以我现在有两个问题:
-我的计数器没有在应用程序启动时启动 -名称是不同的