PerformanceCounterCategory.GetCounters Método

Definición

Recupera una lista de los contadores de esta categoría de contador de rendimiento.

Sobrecargas

GetCounters()

Recupera una lista de los contadores de una categoría de contador de rendimiento que contiene exactamente una instancia.

GetCounters(String)

Recupera una lista de los contadores de una categoría de contador de rendimiento que contiene una o más instancias.

GetCounters()

Source:
PerformanceCounterCategory.cs
Source:
PerformanceCounterCategory.cs
Source:
PerformanceCounterCategory.cs

Recupera una lista de los contadores de una categoría de contador de rendimiento que contiene exactamente una instancia.

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

Devoluciones

Matriz de objetos PerformanceCounter que indica los contadores que están asociados a esta categoría de contador de rendimiento de una sola instancia.

Excepciones

La categoría no es una instancia única.

Se ha producido un error en la llamada a una API del sistema subyacente.

La categoría no tiene una instancia asociada.

Código que se ejecuta sin privilegios administrativos para intentar leer un contador de rendimiento.

Ejemplos

En el ejemplo de código siguiente se obtiene una lista de los PerformanceCounter objetos de .PerformanceCounterCategory En primer lugar, crea un PerformanceCounterCategory objeto con el constructor adecuado, en función de si se especificó un nombre de equipo. A continuación, usa el GetCounters método para devolver una matriz de PerformanceCounter objetos, seleccionando la GetCounters sobrecarga en función de si se especificó un nombre de instancia.

Esta GetCounters() sobrecarga produce un error a menos que se use con una categoría de instancia ú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

Comentarios

Para obtener más información sobre las instancias de objeto de rendimiento, consulte la información general de la PerformanceCounter clase.

Nota

Para leer contadores de rendimiento de una sesión de inicio de sesión no interactiva en Windows Vista y versiones posteriores, Windows XP Professional x64 Edition o Windows Server 2003, debe ser miembro del grupo Usuarios de Monitor de rendimiento o tener privilegios administrativos.

Para evitar tener que elevar los privilegios para acceder a los contadores de rendimiento en Windows Vista y versiones posteriores, agréguese al grupo usuarios de Monitor de rendimiento.

En Windows Vista y versiones posteriores, el Control de cuentas de usuario (UAC) determina los privilegios de un usuario. Si es miembro del grupo Administradores integrados, se le asignarán dos símbolos (tokens) de acceso en tiempo de ejecución: un símbolo (token) de acceso de usuario estándar y un símbolo (token) de acceso de administrador. De forma predeterminada, se le asignará el rol de usuario estándar. Para ejecutar el código que accede a los contadores de rendimiento, primero debe elevar los privilegios del usuario estándar al administrador. Para ello, inicie una aplicación haciendo clic con el botón derecho en el icono de la aplicación e indique que desea ejecutarla como administrador.

Consulte también

Se aplica a

GetCounters(String)

Source:
PerformanceCounterCategory.cs
Source:
PerformanceCounterCategory.cs
Source:
PerformanceCounterCategory.cs

Recupera una lista de los contadores de una categoría de contador de rendimiento que contiene una o más instancias.

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

Instancia de objeto de rendimiento para la que se va a recuperar una lista de contadores asociados.

Devoluciones

Matriz de objetos PerformanceCounter que indica los contadores asociados a la instancia de objeto especificada de esta categoría de contador de rendimiento.

Excepciones

El parámetro instanceName es null.

No se ha establecido la propiedad CategoryName para esta instancia de PerformanceCounterCategory.

o bien

La categoría no contiene la instancia especificada en el parámetro instanceName.

Se ha producido un error en la llamada a una API del sistema subyacente.

Código que se ejecuta sin privilegios administrativos para intentar leer un contador de rendimiento.

Ejemplos

En el ejemplo de código siguiente se obtiene una lista de los PerformanceCounter objetos de .PerformanceCounterCategory En primer lugar, crea un PerformanceCounterCategory objeto con el constructor adecuado, en función de si se especificó un nombre de equipo. A continuación, usa el GetCounters método para devolver una matriz de PerformanceCounter objetos, seleccionando la GetCounters sobrecarga en función de si se especificó un nombre de instancia.

Esta GetCounters(String) sobrecarga produce un error a menos que se use con una categoría que contenga instancias.

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

Comentarios

Para representar una categoría de instancia única, pase una cadena vacía ("") para el instanceName parámetro .

Para obtener más información sobre las instancias de objeto de rendimiento, consulte la información general de la PerformanceCounter clase.

Nota

Para leer contadores de rendimiento de una sesión de inicio de sesión no interactiva en Windows Vista y versiones posteriores, Windows XP Professional x64 Edition o Windows Server 2003, debe ser miembro del grupo Usuarios de Monitor de rendimiento o tener privilegios administrativos.

Para evitar tener que elevar los privilegios para acceder a los contadores de rendimiento en Windows Vista y versiones posteriores, agréguese al grupo usuarios de Monitor de rendimiento.

En Windows Vista y versiones posteriores, el Control de cuentas de usuario (UAC) determina los privilegios de un usuario. Si es miembro del grupo Administradores integrados, se le asignarán dos símbolos (tokens) de acceso en tiempo de ejecución: un símbolo (token) de acceso de usuario estándar y un símbolo (token) de acceso de administrador. De forma predeterminada, se le asignará el rol de usuario estándar. Para ejecutar el código que accede a los contadores de rendimiento, primero debe elevar los privilegios del usuario estándar al administrador. Para ello, inicie una aplicación haciendo clic con el botón derecho en el icono de la aplicación e indique que desea ejecutarla como administrador.

Consulte también

Se aplica a