PerformanceCounterCategory.GetCounters Método

Definição

Recupera uma lista de contadores nessa categoria de contador de desempenho.

Sobrecargas

GetCounters()

Recupera uma lista dos contadores em uma categoria de contador de desempenho que contém exatamente uma instância.

GetCounters(String)

Recupera uma lista dos contadores em uma categoria de contador de desempenho que uma ou mais instância.

GetCounters()

Origem:
PerformanceCounterCategory.cs
Origem:
PerformanceCounterCategory.cs
Origem:
PerformanceCounterCategory.cs

Recupera uma lista dos contadores em uma categoria de contador de desempenho que contém exatamente uma instância.

public:
 cli::array <System::Diagnostics::PerformanceCounter ^> ^ GetCounters();
public System.Diagnostics.PerformanceCounter[] GetCounters ();
member this.GetCounters : unit -> System.Diagnostics.PerformanceCounter[]
Public Function GetCounters () As PerformanceCounter()

Retornos

Uma matriz de objetos PerformanceCounter indicando os contadores que estão associados essa categoria de contador de desempenho de instância única.

Exceções

A categoria não é uma instância única.

Falha ao chamar uma API do sistema subjacente.

A categoria não tem uma instância associada.

Um código em execução sem privilégios administrativos tentou ler um contador de desempenho.

Exemplos

O exemplo de código a PerformanceCounter seguir obtém uma lista dos objetos em um PerformanceCounterCategory. Primeiro, ele cria um PerformanceCounterCategory com o construtor apropriado, com base em se um nome de computador foi especificado. Em seguida, ele usa o GetCounters método para retornar uma matriz de PerformanceCounter objetos, selecionando a GetCounters sobrecarga com base em se um nome de instância foi especificado.

Essa GetCounters() sobrecarga falhará, a menos que seja usada com uma categoria de instância única.

public:
    static void Main(array<String^>^ args)
    {
        String^ categoryName = "";
        String^ machineName = "";
        String^ instanceName = "";
        PerformanceCounterCategory^ pcc;
        array<PerformanceCounter^>^ counters;

        // Copy the supplied arguments into the local variables.
        try
        {
            categoryName = args[1];
            machineName = args[2]=="."? "": args[2];
            instanceName = args[3];
        }
        catch (...)
        {
            // Ignore the exception from non-supplied arguments.
        }

        try
        {
            // Create the appropriate PerformanceCounterCategory object.
            if (machineName->Length>0)
            {
                pcc = gcnew PerformanceCounterCategory(categoryName, machineName);
            }
            else
            {
                pcc = gcnew PerformanceCounterCategory(categoryName);
            }

            // Get the counters for this instance or a single instance
            // of the selected category.
            if (instanceName->Length > 0)
            {
                counters = pcc->GetCounters(instanceName);
            }
            else
            {
                counters = pcc->GetCounters();
            }

        }
        catch (Exception^ ex)
        {
            Console::WriteLine("Unable to get counter information for " +
                (instanceName->Length>0? "instance \"{2}\" in ": "single-instance ") +
                "category \"{0}\" on " + (machineName->Length>0? "computer \"{1}\":": "this computer:"),
                categoryName, machineName, instanceName);
            Console::WriteLine(ex->Message);
            return;
        }

        // Display the counter names if GetCounters was successful.
        if (counters != nullptr)
        {
            Console::WriteLine("These counters exist in " +
                (instanceName->Length > 0 ? "instance \"{1}\" of" : "single instance") +
                " category {0} on " + (machineName->Length > 0 ? "computer \"{2}\":": "this computer:"),
                categoryName, instanceName, machineName);

            // Display a numbered list of the counter names.
            int objX;
            for(objX = 0; objX < counters->Length; objX++)
            {
                Console::WriteLine("{0,4} - {1}", objX + 1, counters[objX]->CounterName);
            }
        }
    }
public static void Main(string[] args)
{
    string categoryName = "";
    string machineName = "";
    string instanceName = "";
    PerformanceCounterCategory pcc;
    PerformanceCounter[] counters;

    // Copy the supplied arguments into the local variables.
    try
    {
        categoryName = args[0];
        machineName = args[1]=="."? "": args[1];
        instanceName = args[2];
    }
    catch
    {
        // Ignore the exception from non-supplied arguments.
    }

    try
    {
        // Create the appropriate PerformanceCounterCategory object.
        if (machineName.Length>0)
        {
            pcc = new PerformanceCounterCategory(categoryName, machineName);
        }
        else
        {
            pcc = new PerformanceCounterCategory(categoryName);
        }

        // Get the counters for this instance or a single instance
        // of the selected category.
        if (instanceName.Length>0)
        {
            counters = pcc.GetCounters(instanceName);
        }
        else
        {
            counters = pcc.GetCounters();
        }
    }
    catch(Exception ex)
    {
        Console.WriteLine("Unable to get counter information for " +
            (instanceName.Length>0? "instance \"{2}\" in ": "single-instance ") +
            "category \"{0}\" on " + (machineName.Length>0? "computer \"{1}\":": "this computer:"),
            categoryName, machineName, instanceName);
        Console.WriteLine(ex.Message);
        return;
    }

    // Display the counter names if GetCounters was successful.
    if (counters!=null)
    {
        Console.WriteLine("These counters exist in " +
            (instanceName.Length>0? "instance \"{1}\" of": "single instance") +
            " category {0} on " + (machineName.Length>0? "computer \"{2}\":": "this computer:"),
            categoryName, instanceName, machineName);

        // Display a numbered list of the counter names.
        int objX;
        for(objX=0; objX<counters.Length; objX++)
        {
            Console.WriteLine("{0,4} - {1}", objX+1, counters[objX].CounterName);
        }
    }
}
Sub Main(ByVal args() As String)
    Dim categoryName As String = ""
    Dim machineName As String = ""
    Dim instanceName As String = ""
    Dim pcc As PerformanceCounterCategory
    Dim counters() As PerformanceCounter

    ' Copy the supplied arguments into the local variables.
    Try
        categoryName = args(0)
        machineName = IIf(args(1) = ".", "", args(1))
        instanceName = args(2)
    Catch ex As Exception
        ' Ignore the exception from non-supplied arguments.
    End Try

    Try
        ' Create the appropriate PerformanceCounterCategory object.
        If machineName.Length > 0 Then
            pcc = New PerformanceCounterCategory(categoryName, machineName)
        Else
            pcc = New PerformanceCounterCategory(categoryName)
        End If

        ' Get the counters for this instance or a single instance 
        ' of the selected category.
        If instanceName.Length > 0 Then
            counters = pcc.GetCounters(instanceName)
        Else
            counters = pcc.GetCounters()
        End If

    Catch ex As Exception
        Console.WriteLine("Unable to get counter information for " & _
            IIf(instanceName.Length > 0, "instance ""{2}"" in ", _
            "single-instance ") & "category ""{0}"" on " & _
            IIf(machineName.Length > 0, "computer ""{1}"":", _
            "this computer:"), _
            categoryName, machineName, instanceName)
        Console.WriteLine(ex.Message)
        Return
    End Try

    ' Display the counter names if GetCounters was successful.
    If Not counters Is Nothing Then
        Console.WriteLine("These counters exist in " & _
            IIf(instanceName.Length > 0, "instance ""{1}"" of", _
            "single instance") & " category {0} on " & _
            IIf(machineName.Length > 0, _
                "computer ""{2}"":", "this computer:"), _
            categoryName, instanceName, machineName)

        ' Display a numbered list of the counter names.
        Dim objX As Integer
        For objX = 0 To counters.Length - 1
            Console.WriteLine("{0,4} - {1}", objX + 1, _
                counters(objX).CounterName)
        Next objX
    End If
End Sub

Comentários

Para obter mais informações sobre instâncias de objeto de desempenho, consulte a visão geral da PerformanceCounter classe.

Observação

Para ler contadores de desempenho de uma sessão de logon não interativa no Windows Vista e posterior, Windows XP Professional x64 Edition ou Windows Server 2003, você deve ser membro do grupo usuários Monitor de Desempenho ou ter privilégios administrativos.

Para evitar ter que elevar seus privilégios para acessar contadores de desempenho no Windows Vista e posterior, adicione-se ao grupo Monitor de Desempenho Usuários.

No Windows Vista e posterior, UAC (Controle de Conta de Usuário) determina os privilégios de um usuário. Se for um membro do grupo Administradores Internos, você receberá dois tokens de acesso do tempo de execução: um token de acesso do usuário padrão e um token de acesso do administrador. Por padrão, você está na função de usuário padrão. Para executar o código que acessa contadores de desempenho, primeiro você deve elevar seus privilégios de usuário padrão para administrador. Você pode fazer isso ao iniciar um aplicativo, clicando com o botão direito do mouse no ícone do aplicativo e indicando que você deseja executar como administrador.

Confira também

Aplica-se a

GetCounters(String)

Origem:
PerformanceCounterCategory.cs
Origem:
PerformanceCounterCategory.cs
Origem:
PerformanceCounterCategory.cs

Recupera uma lista dos contadores em uma categoria de contador de desempenho que uma ou mais instância.

public:
 cli::array <System::Diagnostics::PerformanceCounter ^> ^ GetCounters(System::String ^ instanceName);
public System.Diagnostics.PerformanceCounter[] GetCounters (string instanceName);
member this.GetCounters : string -> System.Diagnostics.PerformanceCounter[]
Public Function GetCounters (instanceName As String) As PerformanceCounter()

Parâmetros

instanceName
String

A instância do objeto de desempenho para o qual recuperar a lista de contadores associados.

Retornos

Uma matriz de objetos PerformanceCounter indicando os contadores que estão associados à instância do objeto especificado dessa categoria de contador de desempenho.

Exceções

O parâmetro instanceName é null.

A propriedade CategoryName para esta instância PerformanceCounterCategory não foi definida.

- ou -

A categoria não contém a instância que é especificada pelo parâmetro instanceName.

Falha ao chamar uma API do sistema subjacente.

Um código em execução sem privilégios administrativos tentou ler um contador de desempenho.

Exemplos

O exemplo de código a PerformanceCounter seguir obtém uma lista dos objetos em um PerformanceCounterCategory. Primeiro, ele cria um PerformanceCounterCategory com o construtor apropriado, com base em se um nome de computador foi especificado. Em seguida, ele usa o GetCounters método para retornar uma matriz de PerformanceCounter objetos, selecionando a GetCounters sobrecarga com base em se um nome de instância foi especificado.

Essa GetCounters(String) sobrecarga falhará, a menos que seja usada com uma categoria que contenha instâncias.

public:
    static void Main(array<String^>^ args)
    {
        String^ categoryName = "";
        String^ machineName = "";
        String^ instanceName = "";
        PerformanceCounterCategory^ pcc;
        array<PerformanceCounter^>^ counters;

        // Copy the supplied arguments into the local variables.
        try
        {
            categoryName = args[1];
            machineName = args[2]=="."? "": args[2];
            instanceName = args[3];
        }
        catch (...)
        {
            // Ignore the exception from non-supplied arguments.
        }

        try
        {
            // Create the appropriate PerformanceCounterCategory object.
            if (machineName->Length>0)
            {
                pcc = gcnew PerformanceCounterCategory(categoryName, machineName);
            }
            else
            {
                pcc = gcnew PerformanceCounterCategory(categoryName);
            }

            // Get the counters for this instance or a single instance
            // of the selected category.
            if (instanceName->Length > 0)
            {
                counters = pcc->GetCounters(instanceName);
            }
            else
            {
                counters = pcc->GetCounters();
            }

        }
        catch (Exception^ ex)
        {
            Console::WriteLine("Unable to get counter information for " +
                (instanceName->Length>0? "instance \"{2}\" in ": "single-instance ") +
                "category \"{0}\" on " + (machineName->Length>0? "computer \"{1}\":": "this computer:"),
                categoryName, machineName, instanceName);
            Console::WriteLine(ex->Message);
            return;
        }

        // Display the counter names if GetCounters was successful.
        if (counters != nullptr)
        {
            Console::WriteLine("These counters exist in " +
                (instanceName->Length > 0 ? "instance \"{1}\" of" : "single instance") +
                " category {0} on " + (machineName->Length > 0 ? "computer \"{2}\":": "this computer:"),
                categoryName, instanceName, machineName);

            // Display a numbered list of the counter names.
            int objX;
            for(objX = 0; objX < counters->Length; objX++)
            {
                Console::WriteLine("{0,4} - {1}", objX + 1, counters[objX]->CounterName);
            }
        }
    }
public static void Main(string[] args)
{
    string categoryName = "";
    string machineName = "";
    string instanceName = "";
    PerformanceCounterCategory pcc;
    PerformanceCounter[] counters;

    // Copy the supplied arguments into the local variables.
    try
    {
        categoryName = args[0];
        machineName = args[1]=="."? "": args[1];
        instanceName = args[2];
    }
    catch
    {
        // Ignore the exception from non-supplied arguments.
    }

    try
    {
        // Create the appropriate PerformanceCounterCategory object.
        if (machineName.Length>0)
        {
            pcc = new PerformanceCounterCategory(categoryName, machineName);
        }
        else
        {
            pcc = new PerformanceCounterCategory(categoryName);
        }

        // Get the counters for this instance or a single instance
        // of the selected category.
        if (instanceName.Length>0)
        {
            counters = pcc.GetCounters(instanceName);
        }
        else
        {
            counters = pcc.GetCounters();
        }
    }
    catch(Exception ex)
    {
        Console.WriteLine("Unable to get counter information for " +
            (instanceName.Length>0? "instance \"{2}\" in ": "single-instance ") +
            "category \"{0}\" on " + (machineName.Length>0? "computer \"{1}\":": "this computer:"),
            categoryName, machineName, instanceName);
        Console.WriteLine(ex.Message);
        return;
    }

    // Display the counter names if GetCounters was successful.
    if (counters!=null)
    {
        Console.WriteLine("These counters exist in " +
            (instanceName.Length>0? "instance \"{1}\" of": "single instance") +
            " category {0} on " + (machineName.Length>0? "computer \"{2}\":": "this computer:"),
            categoryName, instanceName, machineName);

        // Display a numbered list of the counter names.
        int objX;
        for(objX=0; objX<counters.Length; objX++)
        {
            Console.WriteLine("{0,4} - {1}", objX+1, counters[objX].CounterName);
        }
    }
}
Sub Main(ByVal args() As String)
    Dim categoryName As String = ""
    Dim machineName As String = ""
    Dim instanceName As String = ""
    Dim pcc As PerformanceCounterCategory
    Dim counters() As PerformanceCounter

    ' Copy the supplied arguments into the local variables.
    Try
        categoryName = args(0)
        machineName = IIf(args(1) = ".", "", args(1))
        instanceName = args(2)
    Catch ex As Exception
        ' Ignore the exception from non-supplied arguments.
    End Try

    Try
        ' Create the appropriate PerformanceCounterCategory object.
        If machineName.Length > 0 Then
            pcc = New PerformanceCounterCategory(categoryName, machineName)
        Else
            pcc = New PerformanceCounterCategory(categoryName)
        End If

        ' Get the counters for this instance or a single instance 
        ' of the selected category.
        If instanceName.Length > 0 Then
            counters = pcc.GetCounters(instanceName)
        Else
            counters = pcc.GetCounters()
        End If

    Catch ex As Exception
        Console.WriteLine("Unable to get counter information for " & _
            IIf(instanceName.Length > 0, "instance ""{2}"" in ", _
            "single-instance ") & "category ""{0}"" on " & _
            IIf(machineName.Length > 0, "computer ""{1}"":", _
            "this computer:"), _
            categoryName, machineName, instanceName)
        Console.WriteLine(ex.Message)
        Return
    End Try

    ' Display the counter names if GetCounters was successful.
    If Not counters Is Nothing Then
        Console.WriteLine("These counters exist in " & _
            IIf(instanceName.Length > 0, "instance ""{1}"" of", _
            "single instance") & " category {0} on " & _
            IIf(machineName.Length > 0, _
                "computer ""{2}"":", "this computer:"), _
            categoryName, instanceName, machineName)

        ' Display a numbered list of the counter names.
        Dim objX As Integer
        For objX = 0 To counters.Length - 1
            Console.WriteLine("{0,4} - {1}", objX + 1, _
                counters(objX).CounterName)
        Next objX
    End If
End Sub

Comentários

Para representar uma categoria de instância única, passe uma cadeia de caracteres vazia ("") para o instanceName parâmetro .

Para obter mais informações sobre instâncias de objeto de desempenho, consulte a visão geral da PerformanceCounter classe.

Observação

Para ler contadores de desempenho de uma sessão de logon não interativa no Windows Vista e posterior, Windows XP Professional x64 Edition ou Windows Server 2003, você deve ser membro do grupo usuários Monitor de Desempenho ou ter privilégios administrativos.

Para evitar ter que elevar seus privilégios para acessar contadores de desempenho no Windows Vista e posterior, adicione-se ao grupo Monitor de Desempenho Usuários.

No Windows Vista e posterior, UAC (Controle de Conta de Usuário) determina os privilégios de um usuário. Se for um membro do grupo Administradores Internos, você receberá dois tokens de acesso do tempo de execução: um token de acesso do usuário padrão e um token de acesso do administrador. Por padrão, você está na função de usuário padrão. Para executar o código que acessa contadores de desempenho, primeiro você deve elevar seus privilégios de usuário padrão para administrador. Você pode fazer isso ao iniciar um aplicativo, clicando com o botão direito do mouse no ícone do aplicativo e indicando que você deseja executar como administrador.

Confira também

Aplica-se a