PerformanceCounterCategory.Create Método

Definição

Registra uma categoria de contador de desempenho personalizado e um ou mais contadores com o sistema.Registers a custom performance counter category and one or more counters with the system.

Sobrecargas

Create(String, String, String, String)
Obsoleto.
Obsoleto.
Obsoleto.

Registra uma categoria do contador de desempenho personalizado que contém um único contador do tipo NumberOfItems32 no computador local.Registers a custom performance counter category containing a single counter of type NumberOfItems32 on the local computer.

Create(String, String, PerformanceCounterCategoryType, String, String)

Registra a categoria do contador de desempenho personalizado que contém um único contador do tipo NumberOfItems32 no computador local.Registers the custom performance counter category containing a single counter of type NumberOfItems32 on the local computer.

Create(String, String, CounterCreationDataCollection)
Obsoleto.
Obsoleto.
Obsoleto.

Registra a categoria do contador de desempenho personalizado que contém os contadores especificados no computador local.Registers the custom performance counter category containing the specified counters on the local computer.

Create(String, String, PerformanceCounterCategoryType, CounterCreationDataCollection)

Registra a categoria do contador de desempenho personalizado que contém os contadores especificados no computador local.Registers the custom performance counter category containing the specified counters on the local computer.

Create(String, String, String, String)

Cuidado

This method has been deprecated. Please use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, string counterName, string counterHelp) instead. http://go.microsoft.com/fwlink/?linkid=14202

Cuidado

This method has been deprecated. Please use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, string counterName, string counterHelp) instead. https://go.microsoft.com/fwlink/?linkid=14202

Cuidado

Use another overload that uses PerformanceCounterCategoryType instead

Registra uma categoria do contador de desempenho personalizado que contém um único contador do tipo NumberOfItems32 no computador local.Registers a custom performance counter category containing a single counter of type NumberOfItems32 on the local computer.

public:
 static System::Diagnostics::PerformanceCounterCategory ^ Create(System::String ^ categoryName, System::String ^ categoryHelp, System::String ^ counterName, System::String ^ counterHelp);
[System.Obsolete("This method has been deprecated.  Please use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, string counterName, string counterHelp) instead.  http://go.microsoft.com/fwlink/?linkid=14202")]
public static System.Diagnostics.PerformanceCounterCategory Create (string categoryName, string categoryHelp, string counterName, string counterHelp);
[System.Obsolete("This method has been deprecated.  Please use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, string counterName, string counterHelp) instead.  https://go.microsoft.com/fwlink/?linkid=14202")]
public static System.Diagnostics.PerformanceCounterCategory Create (string categoryName, string categoryHelp, string counterName, string counterHelp);
public static System.Diagnostics.PerformanceCounterCategory Create (string categoryName, string categoryHelp, string counterName, string counterHelp);
[System.Obsolete("Use another overload that uses PerformanceCounterCategoryType instead")]
public static System.Diagnostics.PerformanceCounterCategory Create (string categoryName, string categoryHelp, string counterName, string counterHelp);
[<System.Obsolete("This method has been deprecated.  Please use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, string counterName, string counterHelp) instead.  http://go.microsoft.com/fwlink/?linkid=14202")>]
static member Create : string * string * string * string -> System.Diagnostics.PerformanceCounterCategory
[<System.Obsolete("This method has been deprecated.  Please use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, string counterName, string counterHelp) instead.  https://go.microsoft.com/fwlink/?linkid=14202")>]
static member Create : string * string * string * string -> System.Diagnostics.PerformanceCounterCategory
static member Create : string * string * string * string -> System.Diagnostics.PerformanceCounterCategory
[<System.Obsolete("Use another overload that uses PerformanceCounterCategoryType instead")>]
static member Create : string * string * string * string -> System.Diagnostics.PerformanceCounterCategory
Public Shared Function Create (categoryName As String, categoryHelp As String, counterName As String, counterHelp As String) As PerformanceCounterCategory

Parâmetros

categoryName
String

O nome da categoria do contador de desempenho personalizado a ser criada e registrada no sistema.The name of the custom performance counter category to create and register with the system.

categoryHelp
String

Uma descrição da categoria personalizada.A description of the custom category.

counterName
String

O nome de um novo contador, do tipo NumberOfItems32, a ser criado como parte da nova categoria.The name of a new counter, of type NumberOfItems32, to create as part of the new category.

counterHelp
String

Uma descrição do contador associado à nova categoria personalizada.A description of the counter that is associated with the new custom category.

Retornos

PerformanceCounterCategory

Um PerformanceCounterCategory associado à nova categoria do sistema ou ao objeto de desempenho.A PerformanceCounterCategory that is associated with the new system category, or performance object.

Atributos

Exceções

counterName é null ou é uma cadeia de caracteres vazia ("").counterName is null or is an empty string ("").

- ou --or- O contador especificado por counterName já existe.The counter that is specified by counterName already exists.

- ou --or- O counterName tem uma sintaxe inválida.counterName has invalid syntax. Pode conter caracteres de barra invertida ("\") ou ter um tamanho maior que 80 caracteres.It might contain backslash characters ("\") or have length greater than 80 characters.

A categoria já existe no computador local.The category already exists on the local computer.

categoryName é null.categoryName is null.

- ou --or- counterHelp é null.counterHelp is null.

Falha ao chamar uma API do sistema subjacente.A call to an underlying system API failed.

Um código em execução sem privilégios administrativos tentou ler um contador de desempenho.Code that is executing without administrative privileges attempted to read a performance counter.

Exemplos

O exemplo de código a seguir cria um PerformanceCounterCategory e único PerformanceCounter com texto de ajuda para cada um, usando o Create(String, String, String, String) método.The following code example creates a PerformanceCounterCategory and single PerformanceCounter with help text for each, using the Create(String, String, String, String) method.

public static void Main(string[] args)
{
    string categoryName = "";
    string counterName = "";
    string categoryHelp = "";
    string counterHelp = "";
    PerformanceCounterCategory pcc;

    // Copy the supplied arguments into the local variables.
    try
    {
        categoryName = args[0];
        counterName = args[1];
        categoryHelp = args[2];
        counterHelp = args[3];
    }
    catch(Exception ex)
    {
        // Ignore the exception from non-supplied arguments.
    }

    Console.WriteLine("Category name: \"{0}\"", categoryName);
    Console.WriteLine("Category help: \"{0}\"", categoryHelp);
    Console.WriteLine("Counter name:  \"{0}\"", counterName);
    Console.WriteLine("Counter help:  \"{0}\"", counterHelp);

    // Use the Create overload that creates a single counter.
    try
    {
        pcc = PerformanceCounterCategory.Create(categoryName, categoryHelp, counterName, counterHelp);
        Console.WriteLine("Category \"{0}\" created.", pcc.CategoryName);
    }
    catch(Exception ex)
    {
        Console.WriteLine("Unable to create the above category and counter:" + "\n" + ex.Message);
    }
}
Sub Main(ByVal args() As String)
    Dim categoryName As String = ""
    Dim counterName As String = ""
    Dim categoryHelp As String = ""
    Dim counterHelp As String = ""
    Dim pcc As PerformanceCounterCategory

    ' Copy the supplied arguments into the local variables.
    Try
        categoryName = args(0)
        counterName = args(1)
        categoryHelp = args(2)
        counterHelp = args(3)
    Catch ex As Exception
        ' Ignore the exception from non-supplied arguments.
    End Try

    Console.WriteLine("Category name: ""{0}""", categoryName)
    Console.WriteLine("Category help: ""{0}""", categoryHelp)
    Console.WriteLine("Counter name:  ""{0}""", counterName)
    Console.WriteLine("Counter help:  ""{0}""", counterHelp)

    ' Use the Create overload that creates a single counter.
    Try
        pcc = PerformanceCounterCategory.Create( _
            categoryName, categoryHelp, counterName, counterHelp)
        Console.WriteLine("Category ""{0}"" created.", pcc.CategoryName)

    Catch ex As Exception
        Console.WriteLine( _
            "Unable to create the above category and counter:" & _
            vbCrLf & ex.Message)
    End Try
End Sub

Comentários

Observação

Para ler os contadores de desempenho de uma sessão de logon não interativa no Windows Vista e posterior, no Windows XP Professional x64 Edition ou no Windows Server 2003, você deve ser um membro do grupo usuários do monitor de desempenho ou ter privilégios administrativos.To read performance counters from a non-interactive logon session in Windows Vista and later, Windows XP Professional x64 Edition, or Windows Server 2003, you must either be a member of the Performance Monitor Users group or have administrative privileges.

Para evitar a elevação de seus privilégios para acessar os contadores de desempenho no Windows Vista e posterior, adicione-se ao grupo usuários do monitor de desempenho.To avoid having to elevate your privileges to access performance counters in Windows Vista and later, add yourself to the Performance Monitor Users group.

No Windows Vista e posterior, UAC (Controle de Conta de Usuário) determina os privilégios de um usuário.In Windows Vista and later, User Account Control (UAC) determines the privileges of a user. 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.If you are a member of the Built-in Administrators group, you are assigned two run-time access tokens: a standard user access token and an administrator access token. Por padrão, você está na função de usuário padrão.By default, you are in the standard user role. Para executar o código que acessa contadores de desempenho, você deve primeiro elevar seus privilégios do usuário padrão para o administrador.To execute the code that accesses performance counters, you must first elevate your privileges from standard user to administrator. Você pode fazer isso ao iniciar um aplicativo clicando com o botão direito do mouse no ícone do aplicativo e indicando que deseja executar como administrador.You can do this when you start an application by right-clicking the application icon and indicating that you want to run as an administrator.

Confira também

Aplica-se a

Create(String, String, PerformanceCounterCategoryType, String, String)

Registra a categoria do contador de desempenho personalizado que contém um único contador do tipo NumberOfItems32 no computador local.Registers the custom performance counter category containing a single counter of type NumberOfItems32 on the local computer.

public:
 static System::Diagnostics::PerformanceCounterCategory ^ Create(System::String ^ categoryName, System::String ^ categoryHelp, System::Diagnostics::PerformanceCounterCategoryType categoryType, System::String ^ counterName, System::String ^ counterHelp);
public static System.Diagnostics.PerformanceCounterCategory Create (string categoryName, string categoryHelp, System.Diagnostics.PerformanceCounterCategoryType categoryType, string counterName, string counterHelp);
static member Create : string * string * System.Diagnostics.PerformanceCounterCategoryType * string * string -> System.Diagnostics.PerformanceCounterCategory
Public Shared Function Create (categoryName As String, categoryHelp As String, categoryType As PerformanceCounterCategoryType, counterName As String, counterHelp As String) As PerformanceCounterCategory

Parâmetros

categoryName
String

O nome da categoria do contador de desempenho personalizado a ser criada e registrada no sistema.The name of the custom performance counter category to create and register with the system.

categoryHelp
String

Uma descrição da categoria personalizada.A description of the custom category.

categoryType
PerformanceCounterCategoryType

Um dos valores PerformanceCounterCategoryType que especifica se a categoria é MultiInstance, SingleInstance ou Unknown.One of the PerformanceCounterCategoryType values specifying whether the category is MultiInstance, SingleInstance, or Unknown.

counterName
String

O nome de um novo contador a ser criado como parte da nova categoria.The name of a new counter to create as part of the new category.

counterHelp
String

Uma descrição do contador associado à nova categoria personalizada.A description of the counter that is associated with the new custom category.

Retornos

PerformanceCounterCategory

Um PerformanceCounterCategory associado à nova categoria do sistema ou ao objeto de desempenho.A PerformanceCounterCategory that is associated with the new system category, or performance object.

Exceções

counterName é null ou é uma cadeia de caracteres vazia ("").counterName is null or is an empty string ("").

- ou --or- O contador especificado por counterName já existe.The counter that is specified by counterName already exists.

- ou --or- O counterName tem uma sintaxe inválida.counterName has invalid syntax. Pode conter caracteres de barra invertida ("\") ou ter um tamanho maior que 80 caracteres.It might contain backslash characters ("\") or have length greater than 80 characters.

A categoria já existe no computador local.The category already exists on the local computer.

categoryName é null.categoryName is null.

- ou --or- counterHelp é null.counterHelp is null.

Falha ao chamar uma API do sistema subjacente.A call to an underlying system API failed.

Um código em execução sem privilégios administrativos tentou ler um contador de desempenho.Code that is executing without administrative privileges attempted to read a performance counter.

Exemplos

O exemplo de código a seguir mostra o uso do Create método.The following code example shows the use of the Create method. O exemplo mostra como criar uma categoria de contador de desempenho de instância única personalizada.The example shows how to create a custom, single instance performance counter category.

Console.WriteLine("Creating Inventory custom counter");
if (!PerformanceCounterCategory.Exists("Inventory"))
    PerformanceCounterCategory.Create("Inventory",
        "Truck inventory",
        PerformanceCounterCategoryType.SingleInstance,
        "Trucks", "Number of trucks on hand");
Console.WriteLine("Creating Inventory custom counter")
If Not PerformanceCounterCategory.Exists("Inventory") Then
    PerformanceCounterCategory.Create("Inventory", "Truck inventory", PerformanceCounterCategoryType.SingleInstance, "Trucks", "Number of trucks on hand")
End If

Comentários

O categoryType parâmetro especifica se a categoria do contador de desempenho é de instância única ou de várias instâncias.The categoryType parameter specifies whether the performance counter category is single-instance or multi-instance. Por padrão, uma categoria é de instância única quando ela é criada e se torna várias instâncias quando outra instância é adicionada.By default, a category is single-instance when it is created and becomes multi-instance when another instance is added. As categorias são criadas quando um aplicativo é configurado e as instâncias são adicionadas em tempo de execução.Categories are created when an application is set up, and instances are added at run time. No .NET Framework versões 1,0 e 1,1, não é necessário saber se uma categoria de contador de desempenho é de várias instâncias ou de uma única instância.In the .NET Framework versions 1.0 and 1.1, it is not necessary to know if a performance counter category is multi-instance or single-instance. No .NET Framework 2,0, a PerformanceCounterCategoryType enumeração é usada para indicar se um contador de desempenho pode ter várias instâncias.In the .NET Framework 2.0, the PerformanceCounterCategoryType enumeration is used to indicate whether a performance counter can have multiple instances.

As categorias de contador de desempenho instaladas com o .NET Framework 2,0 usam memória compartilhada separada, com cada categoria de contador de desempenho com sua própria memória.Performance counter categories installed with the .NET Framework 2.0 use separate shared memory, with each performance counter category having its own memory. Você pode especificar o tamanho da memória compartilhada separada criando um DWORD chamado FileMappingSize na chave do registro HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ <category name> \Performance.You can specify the size of separate shared memory by creating a DWORD named FileMappingSize in the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\<category name> \Performance. O valor FileMappingSize é definido como o tamanho da memória compartilhada da categoria.The FileMappingSize value is set to the shared memory size of the category. O tamanho padrão é 131072 decimal.The default size is 131072 decimal. Se o valor de FileMappingSize não estiver presente, o fileMappingSize valor do atributo para o performanceCounters elemento especificado no arquivo de Machine.config será usado, causando sobrecarga adicional para o processamento do arquivo de configuração.If the FileMappingSize value is not present, the fileMappingSize attribute value for the performanceCounters element specified in the Machine.config file is used, causing additional overhead for configuration file processing. Você pode perceber uma melhoria de desempenho na inicialização do aplicativo definindo o tamanho do mapeamento do arquivo no registro.You can realize a performance improvement for application startup by setting the file mapping size in the registry.

Observação

É altamente recomendável que novas categorias de contador de desempenho sejam criadas durante a instalação do aplicativo, não durante a execução do aplicativo.It is strongly recommended that new performance counter categories be created during the installation of the application, not during the execution of the application. Isso permite que o sistema operacional Atualize sua lista de categorias de contador de desempenho registradas.This allows time for the operating system to refresh its list of registered performance counter categories. Se a lista não tiver sido atualizada, haverá falha na tentativa de usar a categoria.If the list has not been refreshed, the attempt to use the category will fail.

Observação

Para ler os contadores de desempenho de uma sessão de logon não interativa no Windows Vista e posterior, no Windows XP Professional x64 Edition ou no Windows Server 2003, você deve ser um membro do grupo usuários do monitor de desempenho ou ter privilégios administrativos.To read performance counters from a non-interactive logon session in Windows Vista and later, Windows XP Professional x64 Edition, or Windows Server 2003, you must either be a member of the Performance Monitor Users group or have administrative privileges.

Para evitar a elevação de seus privilégios para acessar os contadores de desempenho no Windows Vista e posterior, adicione-se ao grupo usuários do monitor de desempenho.To avoid having to elevate your privileges to access performance counters in Windows Vista and later, add yourself to the Performance Monitor Users group.

No Windows Vista e posterior, UAC (Controle de Conta de Usuário) determina os privilégios de um usuário.In Windows Vista and later, User Account Control (UAC) determines the privileges of a user. 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.If you are a member of the Built-in Administrators group, you are assigned two run-time access tokens: a standard user access token and an administrator access token. Por padrão, você está na função de usuário padrão.By default, you are in the standard user role. Para executar o código que acessa contadores de desempenho, você deve primeiro elevar seus privilégios do usuário padrão para o administrador.To execute the code that accesses performance counters, you must first elevate your privileges from standard user to administrator. Você pode fazer isso ao iniciar um aplicativo clicando com o botão direito do mouse no ícone do aplicativo e indicando que deseja executar como administrador.You can do this when you start an application by right-clicking the application icon and indicating that you want to run as an administrator.

Confira também

Aplica-se a

Create(String, String, CounterCreationDataCollection)

Cuidado

This method has been deprecated. Please use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData) instead. http://go.microsoft.com/fwlink/?linkid=14202

Cuidado

This method has been deprecated. Please use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData) instead. https://go.microsoft.com/fwlink/?linkid=14202

Cuidado

Use another overload that uses PerformanceCounterCategoryType instead

Registra a categoria do contador de desempenho personalizado que contém os contadores especificados no computador local.Registers the custom performance counter category containing the specified counters on the local computer.

public:
 static System::Diagnostics::PerformanceCounterCategory ^ Create(System::String ^ categoryName, System::String ^ categoryHelp, System::Diagnostics::CounterCreationDataCollection ^ counterData);
[System.Obsolete("This method has been deprecated.  Please use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData) instead.  http://go.microsoft.com/fwlink/?linkid=14202")]
public static System.Diagnostics.PerformanceCounterCategory Create (string categoryName, string categoryHelp, System.Diagnostics.CounterCreationDataCollection counterData);
[System.Obsolete("This method has been deprecated.  Please use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData) instead.  https://go.microsoft.com/fwlink/?linkid=14202")]
public static System.Diagnostics.PerformanceCounterCategory Create (string categoryName, string categoryHelp, System.Diagnostics.CounterCreationDataCollection counterData);
public static System.Diagnostics.PerformanceCounterCategory Create (string categoryName, string categoryHelp, System.Diagnostics.CounterCreationDataCollection counterData);
[System.Obsolete("Use another overload that uses PerformanceCounterCategoryType instead")]
public static System.Diagnostics.PerformanceCounterCategory Create (string categoryName, string categoryHelp, System.Diagnostics.CounterCreationDataCollection counterData);
[<System.Obsolete("This method has been deprecated.  Please use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData) instead.  http://go.microsoft.com/fwlink/?linkid=14202")>]
static member Create : string * string * System.Diagnostics.CounterCreationDataCollection -> System.Diagnostics.PerformanceCounterCategory
[<System.Obsolete("This method has been deprecated.  Please use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData) instead.  https://go.microsoft.com/fwlink/?linkid=14202")>]
static member Create : string * string * System.Diagnostics.CounterCreationDataCollection -> System.Diagnostics.PerformanceCounterCategory
static member Create : string * string * System.Diagnostics.CounterCreationDataCollection -> System.Diagnostics.PerformanceCounterCategory
[<System.Obsolete("Use another overload that uses PerformanceCounterCategoryType instead")>]
static member Create : string * string * System.Diagnostics.CounterCreationDataCollection -> System.Diagnostics.PerformanceCounterCategory
Public Shared Function Create (categoryName As String, categoryHelp As String, counterData As CounterCreationDataCollection) As PerformanceCounterCategory

Parâmetros

categoryName
String

O nome da categoria do contador de desempenho personalizado a ser criada e registrada no sistema.The name of the custom performance counter category to create and register with the system.

categoryHelp
String

Uma descrição da categoria personalizada.A description of the custom category.

counterData
CounterCreationDataCollection

Um CounterCreationDataCollection que especifica os contadores a serem criados como parte da nova categoria.A CounterCreationDataCollection that specifies the counters to create as part of the new category.

Retornos

PerformanceCounterCategory

Um PerformanceCounterCategory associado à nova categoria personalizada ou ao objeto de desempenho.A PerformanceCounterCategory that is associated with the new custom category, or performance object.

Atributos

Exceções

Um nome de contador especificado na coleção counterData é null ou uma cadeia de caracteres vazia ("").A counter name that is specified within the counterData collection is null or an empty string ("").

- ou --or- Um contador especificado na coleção counterData já existe.A counter that is specified within the counterData collection already exists.

- ou --or- O parâmetro counterName tem uma sintaxe inválida.The counterName parameter has invalid syntax. Pode conter caracteres de barra invertida ("\") ou ter um tamanho maior que 80 caracteres.It might contain backslash characters ("\") or have length greater than 80 characters.

O parâmetro categoryName é null.The categoryName parameter is null.

A categoria já existe no computador local.The category already exists on the local computer.

- ou --or- O layout da coleção counterData está incorreto em relação aos contadores base.The layout of the counterData collection is incorrect for base counters. Um contador do tipo AverageCount64, AverageTimer32, CounterMultiTimer, CounterMultiTimerInverse, CounterMultiTimer100Ns, CounterMultiTimer100NsInverse, RawFraction, SampleFraction ou SampleCounter deve ser seguido imediatamente por um dos tipos de contador base (AverageBase, MultiBase, RawBase ou SampleBase).A counter of type AverageCount64, AverageTimer32, CounterMultiTimer, CounterMultiTimerInverse, CounterMultiTimer100Ns, CounterMultiTimer100NsInverse, RawFraction, SampleFraction or SampleCounter has to be immediately followed by one of the base counter types (AverageBase, MultiBase, RawBase, or SampleBase).

Falha ao chamar uma API do sistema subjacente.A call to an underlying system API failed.

Um código em execução sem privilégios administrativos tentou ler um contador de desempenho.Code that is executing without administrative privileges attempted to read a performance counter.

Exemplos

O exemplo de código a seguir determina se um PerformanceCounterCategory objeto chamado "Orders" existe.The following code example determines whether a PerformanceCounterCategory object named "orders" exists. Caso contrário, ele cria o PerformanceCounterCategory objeto usando um CounterCreationDataCollection objeto que contém dois contadores de desempenho.If not, it creates the PerformanceCounterCategory object by using a CounterCreationDataCollection object that contains two performance counters.

if (  !PerformanceCounterCategory::Exists( "Orders" ) )
{
   CounterCreationData^ milk = gcnew CounterCreationData;
   milk->CounterName = "milk";
   milk->CounterType = PerformanceCounterType::NumberOfItems32;

   CounterCreationData^ milkPerSecond = gcnew CounterCreationData;
   milkPerSecond->CounterName = "milk orders/second";
   milkPerSecond->CounterType = PerformanceCounterType::RateOfCountsPerSecond32;

   CounterCreationDataCollection^ ccds = gcnew CounterCreationDataCollection;
   ccds->Add( milkPerSecond );
   ccds->Add( milk );
   PerformanceCounterCategory::Create( "Orders", "Number of processed orders", ccds );
}
if (!PerformanceCounterCategory.Exists("Orders"))
{
    CounterCreationData milk = new CounterCreationData();
    milk.CounterName = "milk";
    milk.CounterType = PerformanceCounterType.NumberOfItems32;

    CounterCreationData milkPerSecond = new CounterCreationData();
    milkPerSecond.CounterName = "milk orders/second";
    milkPerSecond.CounterType = PerformanceCounterType.RateOfCountsPerSecond32;

    CounterCreationDataCollection ccds = new CounterCreationDataCollection();
    ccds.Add(milkPerSecond);
    ccds.Add(milk);

    PerformanceCounterCategory.Create("Orders", "Number of processed orders",
        PerformanceCounterCategoryType.SingleInstance, ccds);
}
If Not PerformanceCounterCategory.Exists("Orders") Then        
    Dim milk As New CounterCreationData()
    milk.CounterName = "milk"
    milk.CounterType = PerformanceCounterType.NumberOfItems32
    
    Dim milkPerSecond As New CounterCreationData()
    milkPerSecond.CounterName = "milk orders/second"
    milkPerSecond.CounterType = PerformanceCounterType.RateOfCountsPerSecond32
    
    Dim ccds As New CounterCreationDataCollection()
    ccds.Add(milkPerSecond)
    ccds.Add(milk)
    
    PerformanceCounterCategory.Create("Orders", "Number of processed orders", _
           PerformanceCounterCategoryType.SingleInstance, ccds)
End If

Comentários

Observação

Para ler os contadores de desempenho de uma sessão de logon não interativa no Windows Vista e posterior, no Windows XP Professional x64 Edition ou no Windows Server 2003, você deve ser um membro do grupo usuários do monitor de desempenho ou ter privilégios administrativos.To read performance counters from a non-interactive logon session in Windows Vista and later, Windows XP Professional x64 Edition, or Windows Server 2003, you must either be a member of the Performance Monitor Users group or have administrative privileges.

Para evitar a elevação de seus privilégios para acessar os contadores de desempenho no Windows Vista e posterior, adicione-se ao grupo usuários do monitor de desempenho.To avoid having to elevate your privileges to access performance counters in Windows Vista and later, add yourself to the Performance Monitor Users group.

No Windows Vista e posterior, UAC (Controle de Conta de Usuário) determina os privilégios de um usuário.In Windows Vista and later, User Account Control (UAC) determines the privileges of a user. 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.If you are a member of the Built-in Administrators group, you are assigned two run-time access tokens: a standard user access token and an administrator access token. Por padrão, você está na função de usuário padrão.By default, you are in the standard user role. Para executar o código que acessa contadores de desempenho, você deve primeiro elevar seus privilégios do usuário padrão para o administrador.To execute the code that accesses performance counters, you must first elevate your privileges from standard user to administrator. Você pode fazer isso ao iniciar um aplicativo clicando com o botão direito do mouse no ícone do aplicativo e indicando que deseja executar como administrador.You can do this when you start an application by right-clicking the application icon and indicating that you want to run as an administrator.

Confira também

Aplica-se a

Create(String, String, PerformanceCounterCategoryType, CounterCreationDataCollection)

Registra a categoria do contador de desempenho personalizado que contém os contadores especificados no computador local.Registers the custom performance counter category containing the specified counters on the local computer.

public:
 static System::Diagnostics::PerformanceCounterCategory ^ Create(System::String ^ categoryName, System::String ^ categoryHelp, System::Diagnostics::PerformanceCounterCategoryType categoryType, System::Diagnostics::CounterCreationDataCollection ^ counterData);
public static System.Diagnostics.PerformanceCounterCategory Create (string categoryName, string categoryHelp, System.Diagnostics.PerformanceCounterCategoryType categoryType, System.Diagnostics.CounterCreationDataCollection counterData);
static member Create : string * string * System.Diagnostics.PerformanceCounterCategoryType * System.Diagnostics.CounterCreationDataCollection -> System.Diagnostics.PerformanceCounterCategory
Public Shared Function Create (categoryName As String, categoryHelp As String, categoryType As PerformanceCounterCategoryType, counterData As CounterCreationDataCollection) As PerformanceCounterCategory

Parâmetros

categoryName
String

O nome da categoria do contador de desempenho personalizado a ser criada e registrada no sistema.The name of the custom performance counter category to create and register with the system.

categoryHelp
String

Uma descrição da categoria personalizada.A description of the custom category.

counterData
CounterCreationDataCollection

Um CounterCreationDataCollection que especifica os contadores a serem criados como parte da nova categoria.A CounterCreationDataCollection that specifies the counters to create as part of the new category.

Retornos

PerformanceCounterCategory

Um PerformanceCounterCategory associado à nova categoria personalizada ou ao objeto de desempenho.A PerformanceCounterCategory that is associated with the new custom category, or performance object.

Exceções

Um nome de contador especificado na coleção counterData é null ou uma cadeia de caracteres vazia ("").A counter name that is specified within the counterData collection is null or an empty string ("").

- ou --or- Um contador especificado na coleção counterData já existe.A counter that is specified within the counterData collection already exists.

- ou --or- O counterName tem uma sintaxe inválida.counterName has invalid syntax. Pode conter caracteres de barra invertida ("\") ou ter um tamanho maior que 80 caracteres.It might contain backslash characters ("\") or have length greater than 80 characters.

categoryName é null.categoryName is null.

- ou --or- counterData é null.counterData is null.

O valor categoryType está fora do intervalo dos seguintes valores: MultiInstance, SingleInstance ou Unknown.categoryType value is outside of the range of the following values: MultiInstance, SingleInstance, or Unknown.

A categoria já existe no computador local.The category already exists on the local computer.

- ou --or- O layout da coleção counterData está incorreto em relação aos contadores base.The layout of the counterData collection is incorrect for base counters. Um contador do tipo AverageCount64, AverageTimer32, CounterMultiTimer, CounterMultiTimerInverse, CounterMultiTimer100Ns, CounterMultiTimer100NsInverse, RawFraction, SampleFraction ou SampleCounter deve ser seguido imediatamente por um dos tipos de contador base (AverageBase, MultiBase, RawBase ou SampleBase).A counter of type AverageCount64, AverageTimer32, CounterMultiTimer, CounterMultiTimerInverse, CounterMultiTimer100Ns, CounterMultiTimer100NsInverse, RawFraction, SampleFraction, or SampleCounter must be immediately followed by one of the base counter types (AverageBase, MultiBase, RawBase, or SampleBase).

Falha ao chamar uma API do sistema subjacente.A call to an underlying system API failed.

Um código em execução sem privilégios administrativos tentou ler um contador de desempenho.Code that is executing without administrative privileges attempted to read a performance counter.

Exemplos

O exemplo de código a seguir mostra o uso do Create método.The following code example shows the use of the Create method. O exemplo mostra como criar uma categoria de contador de desempenho personalizado de várias instâncias para o número de pedidos por segundo.The example shows how to create a custom, multi-instance performance counter category for the number of orders per second.

CounterCreationData data1 = new CounterCreationData("Trucks",
    "Number of orders", PerformanceCounterType.NumberOfItems32);
CounterCreationData data2 = new CounterCreationData("Rate of sales",
    "Orders/second", PerformanceCounterType.RateOfCountsPerSecond32);
CounterCreationDataCollection ccds = new CounterCreationDataCollection();
ccds.Add(data1);
ccds.Add(data2);
Console.WriteLine("Creating Orders custom counter.");
if (!PerformanceCounterCategory.Exists("Orders"))
    PerformanceCounterCategory.Create("Orders",
        "Processed orders",
        PerformanceCounterCategoryType.MultiInstance,
        ccds);
Dim data1 As New CounterCreationData("Trucks", "Number of orders", PerformanceCounterType.NumberOfItems32)
Dim data2 As New CounterCreationData("Rate of sales", "Orders/second", PerformanceCounterType.RateOfCountsPerSecond32)
Dim ccds As New CounterCreationDataCollection()
ccds.Add(data1)
ccds.Add(data2)
Console.WriteLine("Creating Orders custom counter.")
If Not PerformanceCounterCategory.Exists("Orders") Then
    PerformanceCounterCategory.Create("Orders", "Processed orders", PerformanceCounterCategoryType.MultiInstance, ccds)
End If

Comentários

O categoryType parâmetro especifica se a categoria do contador de desempenho é de instância única ou de várias instâncias.The categoryType parameter specifies whether the performance counter category is single-instance or multi-instance. Por padrão, uma categoria é de instância única quando ela é criada e se torna várias instâncias quando outra instância é adicionada.By default, a category is single-instance when it is created and becomes multi-instance when another instance is added. As categorias são criadas quando um aplicativo é configurado e as instâncias são adicionadas em tempo de execução.Categories are created when an application is set up, and instances are added at run time. No .NET Framework versões 1,0 e 1,1, não é necessário saber se uma categoria de contador de desempenho é de várias instâncias ou de uma única instância.In the .NET Framework versions 1.0 and 1.1, it is not necessary to know if a performance counter category is multi-instance or single-instance. No .NET Framework 2,0, a PerformanceCounterCategoryType enumeração é usada para indicar se um contador de desempenho pode ter várias instâncias.In the .NET Framework 2.0, the PerformanceCounterCategoryType enumeration is used to indicate whether a performance counter can have multiple instances.

As categorias de contador de desempenho instaladas com o .NET Framework 2,0 usam memória compartilhada separada, com cada categoria de contador de desempenho com sua própria memória.Performance counter categories installed with the .NET Framework 2.0 use separate shared memory, with each performance counter category having its own memory. Você pode especificar o tamanho da memória compartilhada separada criando um DWORD chamado FileMappingSize na chave do registro HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ <category name> \Performance.You can specify the size of separate shared memory by creating a DWORD named FileMappingSize in the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\<category name> \Performance. O valor FileMappingSize é definido como o tamanho da memória compartilhada da categoria.The FileMappingSize value is set to the shared memory size of the category. O tamanho padrão é 131072 decimal.The default size is 131072 decimal. Se o valor de FileMappingSize não estiver presente, o fileMappingSize valor do atributo para o performanceCounters elemento especificado no arquivo de Machine.config será usado, causando sobrecarga adicional para o processamento do arquivo de configuração.If the FileMappingSize value is not present, the fileMappingSize attribute value for the performanceCounters element specified in the Machine.config file is used, causing additional overhead for configuration file processing. Você pode perceber uma melhoria de desempenho na inicialização do aplicativo definindo o tamanho do mapeamento do arquivo no registro.You can realize a performance improvement for application startup by setting the file mapping size in the registry.

Observação

É altamente recomendável que novas categorias de contador de desempenho sejam criadas durante a instalação do aplicativo, não durante a execução do aplicativo.It is strongly recommended that new performance counter categories be created during the installation of the application, not during the execution of the application. Isso permite que o sistema operacional Atualize sua lista de categorias de contador de desempenho registradas.This allows time for the operating system to refresh its list of registered performance counter categories. Se a lista não tiver sido atualizada, haverá falha na tentativa de usar a categoria.If the list has not been refreshed, the attempt to use the category will fail.

Observação

Para ler os contadores de desempenho de uma sessão de logon não interativa no Windows Vista e posterior, no Windows XP Professional x64 Edition ou no Windows Server 2003, você deve ser um membro do grupo usuários do monitor de desempenho ou ter privilégios administrativos.To read performance counters from a non-interactive logon session in Windows Vista and later, Windows XP Professional x64 Edition, or Windows Server 2003, you must either be a member of the Performance Monitor Users group or have administrative privileges.

Para evitar a elevação de seus privilégios para acessar os contadores de desempenho no Windows Vista e posterior, adicione-se ao grupo usuários do monitor de desempenho.To avoid having to elevate your privileges to access performance counters in Windows Vista and later, add yourself to the Performance Monitor Users group.

No Windows Vista e posterior, UAC (Controle de Conta de Usuário) determina os privilégios de um usuário.In Windows Vista and later, User Account Control (UAC) determines the privileges of a user. 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.If you are a member of the Built-in Administrators group, you are assigned two run-time access tokens: a standard user access token and an administrator access token. Por padrão, você está na função de usuário padrão.By default, you are in the standard user role. Para executar o código que acessa contadores de desempenho, você deve primeiro elevar seus privilégios do usuário padrão para o administrador.To execute the code that accesses performance counters, you must first elevate your privileges from standard user to administrator. Você pode fazer isso ao iniciar um aplicativo clicando com o botão direito do mouse no ícone do aplicativo e indicando que deseja executar como administrador.You can do this when you start an application by right-clicking the application icon and indicating that you want to run as an administrator.

Confira também

Aplica-se a