PerformanceCounterCategory.GetInstanceNames Método

Definición

Recupera la lista de instancias de objetos de rendimiento asociados a esta categoría.

public:
 cli::array <System::String ^> ^ GetInstanceNames();
public string[] GetInstanceNames ();
member this.GetInstanceNames : unit -> string[]
Public Function GetInstanceNames () As String()

Devoluciones

String[]

Matriz de cadenas que representa los nombres de las instancias de objetos de rendimiento que están asociadas a esta categoría o, si la categoría contiene una sola instancia de objeto de rendimiento, matriz de una sola entrada que contiene una cadena vacía ("").

Excepciones

La propiedad CategoryName es null. Es posible que no se haya establecido la propiedad.

o bien

La categoría no tiene una instancia asociada.

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 utilizando el constructor adecuado en función de si se especificó un nombre de equipo. A continuación, usa GetInstanceNames para devolver los nombres de instancia como una matriz de String, que ordena y muestra.

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

        // Copy the supplied arguments into the local variables.
        try
        {
            categoryName = args[1];
            machineName = args[2]=="."? "": args[2];
        }
        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 instances associated with this category.
            instances = pcc->GetInstanceNames();

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

        //If an empty array is returned, the category has a single instance.
        if (instances->Length==0)
        {
            Console::WriteLine("Category \"{0}\" on " +
                (machineName->Length>0? "computer \"{1}\"": "this computer") +
                " is single-instance.", pcc->CategoryName, pcc->MachineName);
        }
        else
        {
            // Otherwise, display the instances.
            Console::WriteLine("These instances exist in category \"{0}\" on " +
                (machineName->Length>0? "computer \"{1}\".": "this computer:"),
                pcc->CategoryName, pcc->MachineName);

            Array::Sort(instances);
            int objX;
            for (objX = 0; objX < instances->Length; objX++)
            {
                Console::WriteLine("{0,4} - {1}", objX+1, instances[objX]);
            }
        }
    }
public static void Main(string[] args)
{
    string categoryName = "";
    string machineName = "";
    PerformanceCounterCategory pcc;
    string[] instances;

    // Copy the supplied arguments into the local variables.
    try
    {
        categoryName = args[0];
        machineName = args[1]=="."? "": args[1];
    }
    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 instances associated with this category.
        instances = pcc.GetInstanceNames();
    }
    catch(Exception ex)
    {
        Console.WriteLine("Unable to get instance information for " +
            "category \"{0}\" on " +
            (machineName.Length>0? "computer \"{1}\":": "this computer:"),
            categoryName, machineName);
        Console.WriteLine(ex.Message);
        return;
    }

    //If an empty array is returned, the category has a single instance.
    if (instances.Length==0)
    {
        Console.WriteLine("Category \"{0}\" on " +
            (machineName.Length>0? "computer \"{1}\"": "this computer") +
            " is single-instance.", pcc.CategoryName, pcc.MachineName);
    }
    else
    {
        // Otherwise, display the instances.
        Console.WriteLine("These instances exist in category \"{0}\" on " +
            (machineName.Length>0? "computer \"{1}\".": "this computer:"),
            pcc.CategoryName, pcc.MachineName);

        Array.Sort(instances);
        int objX;
        for(objX=0; objX<instances.Length; objX++)
        {
            Console.WriteLine("{0,4} - {1}", objX+1, instances[objX]);
        }
    }
}
Sub Main(ByVal args() As String)
    Dim categoryName As String = ""
    Dim machineName As String = ""
    Dim pcc As PerformanceCounterCategory
    Dim instances() As String

    ' Copy the supplied arguments into the local variables.
    Try
        categoryName = args(0)
        machineName = IIf(args(1) = ".", "", args(1))
    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 instances associated with this category.
        instances = pcc.GetInstanceNames()

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

    'If an empty array is returned, the category has a single instance.
    If instances.Length = 0 Then
        Console.WriteLine( _
            "Category ""{0}"" on " & IIf(machineName.Length > 0, _
            "computer ""{1}""", "this computer") & _
            " is single-instance.", pcc.CategoryName, pcc.MachineName)
    Else
        ' Otherwise, display the instances.
        Console.WriteLine( _
            "These instances exist in category ""{0}"" on " & _
            IIf(machineName.Length > 0, _
                "computer ""{1}"".", "this computer:"), _
            pcc.CategoryName, pcc.MachineName)

        Array.Sort(instances)
        Dim objX As Integer
        For objX = 0 To instances.Length - 1
            Console.WriteLine("{0,4} - {1}", objX + 1, instances(objX))
        Next objX
    End If
End Sub

Comentarios

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.

Se aplica a

Consulte también