Не удается подключиться к сетевому адаптеру на одной виртуальной машине, такой же код работает на другой виртуальной машине - PullRequest
0 голосов
/ 10 июня 2011

Мне нужно получить счетчики производительности от сетевой карты.Чтобы упростить задачу, пользователь выбирает нужный адаптер, набирая индексный номер в консольном приложении.

Console application

Это код, который получает пользовательский ввод и создает экземпляр счетчика производительности.

var connectionNames = NetworkCardLocator.GetConnectedCardNames().ToArray();
log.Debug("Please select one of the available connections");
log.Debug("--");
for (int i = 0; i < connectionNames.Count(); i++)
{
    log.Debug(i + ". " + connectionNames[i]);
}
log.Debug("--");
var key = Console.ReadLine();
int idx = 0;
Int32.TryParse(key, out idx);
string connectionName = connectionNames[idx];

var networkBytesSent = new PerformanceCounter("Network Interface", "Bytes Sent/sec", connectionName);
var networkBytesReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", connectionName);
var networkBytesTotal = new PerformanceCounter("Network Interface", "Bytes Total/sec", connectionName);

Так я выбираю доступные адаптеры

internal static IEnumerable<string> GetConnectedCardNames()
{
    string query = String.Format(@"SELECT * FROM Win32_NetworkAdapter");
    var searcher = new ManagementObjectSearcher
    {
        Query = new ObjectQuery(query)
    };

    try
    {
        log.Debug("Trying to select network adapters");
        var adapterObjects = searcher.Get();

        var names = (from ManagementObject o in adapterObjects
                        select o["Name"])
                            .Cast<string>();

        return names;
    }
    catch (Exception ex)
    {
        log.Debug("Failed to get needed names, see Exception log for details");
        log.Fatal(ex);
        throw;
    }
}

Проблема
Если я выбрал нужный адаптер, код работает на моей машине (Win 2008 R2 Ent x64).Он не работает на некоторых виртуальных машинах, которые я использую для тестирования (Win 2008 R1 DC x86).Любой выбор дает мне исключение (все еще работает на моем ПК и VM Win 2008 R1 Std x86)

foreach (PerformanceCounter counter in counters)
{
    float rawValue = counter.NextValue(); //thrown here
    ...
}

2011-06-10 11:08:20,505 [10] DEBUG TH.Exceptions Instance 'WAN Miniport (PPTP)' does not exist in the specified Category.
System.InvalidOperationException: Instance 'WAN Miniport (PPTP)' does not exist in the specified Category.
   at System.Diagnostics.CounterDefinitionSample.GetInstanceValue(String instanceName)
   at System.Diagnostics.PerformanceCounter.NextSample()
   at System.Diagnostics.PerformanceCounter.NextValue()
   at TH.PerformanceMonitor.API.Internal.PerformanceLogService.DoPerformanceLogging(IEnumerable`1 counters, Int32 interval, TimeSpan duration) in C:\Projects\...\PerformanceLogService.cs:line 122
   at TH.PerformanceMonitor.API.PerformanceManager.DoPerformanceLogging() in C:\Projects\...\PerformanceManager.cs:line 294
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

Q
В чем может быть проблема или как я могупроследить причины?

1 Ответ

0 голосов
/ 10 июня 2011

Проблема была в фантомных сетевых адаптерах .Как только они были удалены с ВМ, все начало работать.

...