Отсутствует сеть отправлено/получено

Я слежу за ответом здесь:

Расчет пропускной способности

И реализовал все, как он сказал. Мой монитор инициализирован так :

netSentCounter.CategoryName = ".NET CLR Networking";
netSentCounter.CounterName = "Bytes Sent";
netSentCounter.InstanceName = Misc.GetInstanceName();
netSentCounter.ReadOnly = true;

, что я правильно вижу, что Misc.GetInstanceName()возвращает «MyProcessName [id]». Однако я продолжаю получать исключение, что экземпляр не существует в указанной категории.

Насколько я понимаю, категория для чистой отправки/получения не создается до тех пор, пока вы не отправите или не получите сообщение.

Я добавил app.config, как описано в ответе, вот так:



    
        
            
        
    

Почему я все еще получаю сообщение об ошибке?

Вот мой код мониторинга:

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;
    }

    /// 
    /// Returns the amount of data sent from the current application in MB
    /// 
    /// 
    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);
    }

    /// 
    /// Returns an assembly name
    /// 
    /// 
    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 это установлено.

Вот что я вижу (это до и после того, как мое приложение отправляет сетевую активность)

enter image description here

И имя не то, что возвращает мой метод. Мой метод возвращает "SuperScraper[appId]", а в ресурсе он называется "Superscraper.vshost.exe".

Теперь у меня две проблемы.:

-Мой счетчик не запускается при запуске приложения. -Имя отличается

0
задан Community 23 May 2017 в 10:30
поделиться