PerformanceCounterCategory Classe
Definição
Representa um objeto de desempenho, que define uma categoria de contadores de desempenho.Represents a performance object, which defines a category of performance counters.
public ref class PerformanceCounterCategory sealed
public sealed class PerformanceCounterCategory
type PerformanceCounterCategory = class
Public NotInheritable Class PerformanceCounterCategory
- Herança
-
PerformanceCounterCategory
Exemplos
O exemplo de código a seguir determina se um PerformanceCounter e seu PerformanceCounterCategory existem no computador local ou em outro computador.The following code example determines whether a PerformanceCounter and its PerformanceCounterCategory exist on the local computer or on another computer. Se esses objetos não existirem no computador local, o exemplo o criará opcionalmente.If these objects do not exist on the local computer, the example optionally creates them. Ele usa o Exists método para determinar se o PerformanceCounterCategory existe.It uses the Exists method to determine whether the PerformanceCounterCategory exists. Se o não PerformanceCounterCategory existir e nenhum nome de contador for especificado, ou se o computador for um computador remoto, o exemplo será encerrado.If the PerformanceCounterCategory does not exist and no counter name is specified, or if the computer is a remote machine, the example exits.
Se um PerformanceCounter nome for fornecido, o exemplo usará o CounterExists método e exibirá o resultado para o usuário.If a PerformanceCounter name is provided, the example uses the CounterExists method and displays the result to the user. Se o não PerformanceCounter existir, o usuário poderá excluir e recriar o PerformanceCounterCategory com o novo PerformanceCounter .If the PerformanceCounter does not exist, the user can delete and re-create the PerformanceCounterCategory with the new PerformanceCounter. Se o usuário faz isso, a categoria é excluída usando o Delete método.If the user does so, the category is deleted using the Delete method.
Se solicitado, o exemplo agora cria o novo PerformanceCounterCategory e PerformanceCounter usando o Create método.If requested, the example now creates the new PerformanceCounterCategory and PerformanceCounter using the Create method. Se um nome de instância for especificado, o exemplo usará o InstanceExists método e exibirá o resultado.If an instance name is specified, the example uses the InstanceExists method and displays the result.
using System;
using System.Diagnostics;
using Microsoft.VisualBasic;
class PerfCounterCatCreateExistMod
{
public static void Main(string[] args)
{
string categoryName = "";
string counterName = "";
string instanceName = "";
string machineName = "";
string categoryHelp = "";
string counterHelp = "";
bool objectExists = false;
PerformanceCounterCategory pcc;
bool createCategory = false;
// Copy the supplied arguments into the local variables.
try
{
categoryName = args[0];
counterName = args[1];
instanceName = args[2];
machineName = args[3]=="."? "": args[3];
categoryHelp = args[4];
counterHelp = args[5];
}
catch(Exception ex)
{
// Ignore the exception from non-supplied arguments.
}
// Verify that the category name is not blank.
if (categoryName.Length==0)
{
Console.WriteLine("Category name cannot be blank.");
return;
}
// Check whether the specified category exists.
if (machineName.Length==0)
{
objectExists = PerformanceCounterCategory.Exists(categoryName);
}
else
{
// Handle the exception that is thrown if the computer
// cannot be found.
try
{
objectExists = PerformanceCounterCategory.Exists(categoryName, machineName);
}
catch(Exception ex)
{
Console.WriteLine("Error checking for existence of " +
"category \"{0}\" on computer \"{1}\":"+"\n" +ex.Message, categoryName, machineName);
return;
}
}
// Tell the user whether the specified category exists.
Console.WriteLine("Category \"{0}\" "+ (objectExists? "exists on ": "does not exist on ")+
(machineName.Length>0? "computer \"{1}\".": "this computer."), categoryName, machineName);
// If no counter name is given, the program cannot continue.
if (counterName.Length==0)
{
return;
}
// A category can only be created on the local computer.
if (!objectExists)
{
if (machineName.Length>0)
{
return;
}
else
{
createCategory = true;
}
}
else
{
// Check whether the specified counter exists.
if (machineName.Length==0)
{
objectExists = PerformanceCounterCategory.CounterExists(counterName, categoryName);
}
else
{
objectExists = PerformanceCounterCategory.CounterExists(counterName, categoryName, machineName);
}
// Tell the user whether the counter exists.
Console.WriteLine("Counter \"{0}\" "+(objectExists? "exists": "does not exist")+
" in category \"{1}\" on "+(machineName.Length>0? "computer \"{2}\".": "this computer."),
counterName, categoryName, machineName);
// If the counter does not exist, consider creating it.
if (!objectExists)
// If this is a remote computer,
// exit because the category cannot be created.
{
if (machineName.Length>0)
{
return;
}
else
{
// Ask whether the user wants to recreate the category.
Console.Write("Do you want to delete and recreate " +
"category \"{0}\" with your new counter? [Y/N]: ", categoryName);
string userReply = Console.ReadLine();
// If yes, delete the category so it can be recreated later.
if (userReply.Trim().ToUpper()=="Y")
{
PerformanceCounterCategory.Delete(categoryName);
createCategory = true;
}
else
{
return;
}
}
}
}
// Create the category if it was deleted or it never existed.
if (createCategory)
{
pcc = PerformanceCounterCategory.Create(categoryName, categoryHelp, counterName, counterHelp);
Console.WriteLine("Category \"{0}\" with counter \"{1}\" created.", pcc.CategoryName, counterName);
}
else if(instanceName.Length>0)
{
if (machineName.Length==0)
{
objectExists = PerformanceCounterCategory.InstanceExists(instanceName, categoryName);
}
else
{
objectExists = PerformanceCounterCategory.InstanceExists(instanceName, categoryName, machineName);
}
// Tell the user whether the instance exists.
Console.WriteLine("Instance \"{0}\" "+(objectExists? "exists": "does not exist")+
" in category \"{1}\" on " + (machineName.Length>0? "computer \"{2}\".": "this computer."),
instanceName, categoryName, machineName);
}
}
}
Imports System.Diagnostics
Module PerfCounterCatCreateExistMod
Sub Main(ByVal args() As String)
Dim categoryName As String = ""
Dim counterName As String = ""
Dim instanceName As String = ""
Dim machineName As String = ""
Dim categoryHelp As String = ""
Dim counterHelp As String = ""
Dim objectExists As Boolean = False
Dim pcc As PerformanceCounterCategory
Dim createCategory As Boolean = False
' Copy the supplied arguments into the local variables.
Try
categoryName = args(0)
counterName = args(1)
instanceName = args(2)
machineName = IIf(args(3) = ".", "", args(3))
categoryHelp = args(4)
counterHelp = args(5)
Catch ex As Exception
' Ignore the exception from non-supplied arguments.
End Try
' Verify that the category name is not blank.
If categoryName.Length = 0 Then
Console.WriteLine("Category name cannot be blank.")
Return
End If
' Check whether the specified category exists.
If machineName.Length = 0 Then
objectExists = _
PerformanceCounterCategory.Exists(categoryName)
Else
' Handle the exception that is thrown if the computer
' cannot be found.
Try
objectExists = PerformanceCounterCategory.Exists( _
categoryName, machineName)
Catch ex As Exception
Console.WriteLine("Error checking for existence of " & _
"category ""{0}"" on computer ""{1}"":" & vbCrLf & _
ex.Message, categoryName, machineName)
Return
End Try
End If
' Tell the user whether the specified category exists.
Console.WriteLine("Category ""{0}"" " & _
IIf(objectExists, "exists on ", "does not exist on ") & _
IIf(machineName.Length > 0, _
"computer ""{1}"".", "this computer."), _
categoryName, machineName)
' If no counter name is given, the program cannot continue.
If counterName.Length = 0 Then
Return
End If
' A category can only be created on the local computer.
If Not objectExists Then
If machineName.Length > 0 Then
Return
Else
createCategory = True
End If
Else
' Check whether the specified counter exists.
If machineName.Length = 0 Then
objectExists = PerformanceCounterCategory.CounterExists( _
counterName, categoryName)
Else
objectExists = PerformanceCounterCategory.CounterExists( _
counterName, categoryName, machineName)
End If
' Tell the user whether the counter exists.
Console.WriteLine("Counter ""{0}"" " & _
IIf(objectExists, "exists", "does not exist") & _
" in category ""{1}"" on " & _
IIf(machineName.Length > 0, _
"computer ""{2}"".", "this computer."), _
counterName, categoryName, machineName)
' If the counter does not exist, consider creating it.
If Not objectExists Then
' If this is a remote computer,
' exit because the category cannot be created.
If machineName.Length > 0 Then
Return
Else
' Ask whether the user wants to recreate the category.
Console.Write("Do you want to delete and recreate " & _
"category ""{0}"" with your new counter? [Y/N]: ", _
categoryName)
Dim userReply As String = Console.ReadLine()
' If yes, delete the category so it can be recreated later.
If userReply.Trim.ToUpper.Chars(0) = "Y" Then
PerformanceCounterCategory.Delete(categoryName)
createCategory = True
Else
Return
End If
End If
End If
End If
' Create the category if it was deleted or it never existed.
If createCategory Then
pcc = PerformanceCounterCategory.Create( _
categoryName, categoryHelp, counterName, counterHelp)
Console.WriteLine( _
"Category ""{0}"" with counter ""{1}"" created.", _
pcc.CategoryName, counterName)
ElseIf instanceName.Length > 0 Then
' If an instance name was given, check whether it exists.
If machineName.Length = 0 Then
objectExists = PerformanceCounterCategory.InstanceExists( _
instanceName, categoryName)
Else
objectExists = PerformanceCounterCategory.InstanceExists( _
instanceName, categoryName, machineName)
End If
' Tell the user whether the instance exists.
Console.WriteLine("Instance ""{0}"" " & _
IIf(objectExists, "exists", "does not exist") & _
" in category ""{1}"" on " & _
IIf(machineName.Length > 0, _
"computer ""{2}"".", "this computer."), _
instanceName, categoryName, machineName)
End If
End Sub
End Module
Comentários
Importante
Criar ou excluir um contador de desempenho requer a sincronização do código subjacente usando um mutex nomeado.Creating or deleting a performance counter requires synchronization of the underlying code by using a named mutex. Se um aplicativo altamente privilegiado bloquear o mutex nomeado, o tentará criar ou excluir um contador de desempenho fará com que o aplicativo pare de responder até que o bloqueio seja liberado.If a highly privileged application locks the named mutex, attempts to create or delete a performance counter causes the application to stop responding until the lock is released. Para ajudar a evitar esse problema, nunca conceda UnmanagedCode permissão a código não confiável.To help avoid this problem, never grant UnmanagedCode permission to untrusted code. Além disso, UnmanagedCode a permissão potencialmente permite que outras permissões sejam ignoradas e só devem ser concedidas a código altamente confiável.In addition, UnmanagedCode permission potentially allows other permissions to be bypassed and should only be granted to highly trusted code.
A PerformanceCounterCategory propriedade da instância CategoryName é exibida no campo objeto de desempenho da caixa de diálogo Adicionar contador do aplicativo visualizador de desempenho.The PerformanceCounterCategory instance's CategoryName property is displayed in the Performance Object field of the Performance Viewer application's Add Counter dialog box.
A PerformanceCounterCategory classe fornece vários métodos para interagir com contadores e categorias no computador.The PerformanceCounterCategory class provides several methods for interacting with counters and categories on the computer. Os Create métodos permitem que você defina categorias personalizadas.The Create methods enable you to define custom categories. O Delete método fornece uma maneira de remover categorias do computador.The Delete method provides a way to remove categories from the computer. O GetCategories método permite que você exiba a lista de categorias, enquanto ReadCategory recupera todos os dados de contador e instância associados a uma única categoria.The GetCategories method enables you to view the list of categories, while ReadCategory retrieves all the counter and instance data associated with a single category.
Um contador de desempenho publica dados de desempenho sobre um aplicativo.A performance counter publishes performance data about an application. As categorias incluem componentes físicos (como processadores, discos e memória) e objetos do sistema (como processos e threads).Categories include physical components (such as processors, disks, and memory) and system objects (such as processes and threads). Os contadores de sistema relacionados ao mesmo objeto de desempenho são agrupados em uma categoria que indica seu foco comum.System counters that are related to the same performance object are grouped into a category that indicates their common focus. Ao criar uma instância da PerformanceCounter classe, você primeiro indica a categoria com a qual o componente irá interagir e, em seguida, escolhe um contador dessa categoria.When you create an instance of the PerformanceCounter class, you first indicate the category with which the component will interact, and then you choose a counter from that category.
Por exemplo, uma categoria de contador do Windows é a categoria de memória.For example, one Windows counter category is the Memory category. Os contadores de sistema nessa categoria controlam os dados de memória, como o número de bytes disponíveis e o número de bytes armazenados em cache.System counters within this category track memory data such as the number of bytes available and the number of bytes cached. Se você quisesse trabalhar com os bytes armazenados em cache em seu aplicativo, crie uma instância do PerformanceCounter componente, conecte-o à categoria memória e, em seguida, escolha o contador apropriado (nesse caso, bytes armazenados em cache) dessa categoria.If you wanted to work with the bytes cached in your application, you would create an instance of the PerformanceCounter component, connect it to the Memory category, and then pick the appropriate counter (in this case, Cached Bytes) from that category.
Embora o sistema disponibilize muito mais categorias de contador, as categorias que você provavelmente interagirão com mais frequência são as categorias cache, memória, objetos, disco físico, processo, processador, servidor, sistema e thread.Although your system makes many more counter categories available, the categories that you will probably interact with most frequently are the Cache, Memory, Objects, PhysicalDisk, Process, Processor, Server, System, and Thread categories.
Importante
O RemoveInstance método na PerformanceCounter classe liberará o contador e, se a opção de reutilização for selecionada para essa categoria, a instância do contador será reutilizada.The RemoveInstance method in the PerformanceCounter class will release the counter and, if the reuse option is selected for that category, the instance of the counter will be reused. Isso pode causar uma condição de corrida se outro processo ou até mesmo outra parte do código estiver tentando gravar na instância do contador.This could cause a race condition if another process or even another part of the code is trying to write to the counter instance.
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
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. Para obter mais informações sobre o tamanho do mapeamento de arquivo, consulte < PerformanceCounters > .For more information about the file mapping size, see <performanceCounters>.
Construtores
| PerformanceCounterCategory() |
Inicializa uma nova instância da classe PerformanceCounterCategory, deixa a propriedade CategoryName vazia e define a propriedade MachineName para o computador local.Initializes a new instance of the PerformanceCounterCategory class, leaves the CategoryName property empty, and sets the MachineName property to the local computer. |
| PerformanceCounterCategory(String) |
Inicializa uma nova instância da classe PerformanceCounterCategory define a propriedade CategoryName como o valor especificado e define a propriedade MachineName para o computador local.Initializes a new instance of the PerformanceCounterCategory class, sets the CategoryName property to the specified value, and sets the MachineName property to the local computer. |
| PerformanceCounterCategory(String, String) |
Inicializa uma nova instância da classe PerformanceCounterCategory e define as propriedades CategoryName e MachineName para os valores especificados.Initializes a new instance of the PerformanceCounterCategory class and sets the CategoryName and MachineName properties to the specified values. |
Propriedades
| CategoryHelp |
Obtém o texto de ajuda da categoria.Gets the category's help text. |
| CategoryName |
Obtém ou define o nome do objeto de desempenho que define essa categoria.Gets or sets the name of the performance object that defines this category. |
| CategoryType |
Obtém o tipo de categoria de contador de desempenho.Gets the performance counter category type. |
| MachineName |
Obtém ou define o nome do computador no qual esta categoria existe.Gets or sets the name of the computer on which this category exists. |
Métodos
| CounterExists(String) |
Determina se o contador especificado está registrado para essa categoria, o que é indicado pelas propriedades CategoryName e MachineName.Determines whether the specified counter is registered to this category, which is indicated by the CategoryName and MachineName properties. |
| CounterExists(String, String) |
Determina se o contador especificado está registrado para a categoria especificada no computador local.Determines whether the specified counter is registered to the specified category on the local computer. |
| CounterExists(String, String, String) |
Determina se o contador especificado está registrado para a categoria especificada em um computador remoto.Determines whether the specified counter is registered to the specified category on a remote 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, 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, String, String) |
Obsoleto.
Obsoleto.
Obsoleto.
Registra uma categoria do contador de desempenho personalizado que contém um único contador do tipo |
| Delete(String) |
Remove a categoria e seus contadores associados do computador local.Removes the category and its associated counters from the local computer. |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object. (Herdado de Object) |
| Exists(String) |
Determina se a categoria está registrada no computador local.Determines whether the category is registered on the local computer. |
| Exists(String, String) |
Determina se a categoria está registrada em um computador especificado.Determines whether the category is registered on the specified computer. |
| GetCategories() |
Recupera uma lista das categorias de contador de desempenho registradas no computador local.Retrieves a list of the performance counter categories that are registered on the local computer. |
| GetCategories(String) |
Recupera uma lista das categorias de contador de desempenho que são registradas no computador especificado.Retrieves a list of the performance counter categories that are registered on the specified computer. |
| GetCounters() |
Recupera uma lista dos contadores em uma categoria de contador de desempenho que contém exatamente uma instância.Retrieves a list of the counters in a performance counter category that contains exactly one instance. |
| GetCounters(String) |
Recupera uma lista dos contadores em uma categoria de contador de desempenho que uma ou mais instância.Retrieves a list of the counters in a performance counter category that contains one or more instances. |
| GetHashCode() |
Serve como a função de hash padrão.Serves as the default hash function. (Herdado de Object) |
| GetInstanceNames() |
Recupera a lista de instâncias de objetos de desempenho associados essa categoria.Retrieves the list of performance object instances that are associated with this category. |
| GetType() |
Obtém o Type da instância atual.Gets the Type of the current instance. (Herdado de Object) |
| InstanceExists(String) |
Determina se a instância do objeto de desempenho especificado existe na categoria identificada por este objeto PerformanceCounterCategory, propriedade CategoryName.Determines whether the specified performance object instance exists in the category that is identified by this PerformanceCounterCategory object's CategoryName property. |
| InstanceExists(String, String) |
Determina se uma categoria especificada no computador local contém a instância do objeto de desempenho especificado.Determines whether a specified category on the local computer contains the specified performance object instance. |
| InstanceExists(String, String, String) |
Determina se uma categoria especificada em um computador especificado contém a instância do objeto de desempenho especificado.Determines whether a specified category on a specified computer contains the specified performance object instance. |
| MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
| ReadCategory() |
Lê todos os contadores e dados de instância do objeto de desempenho associados essa categoria de contador de desempenho.Reads all the counter and performance object instance data that is associated with this performance counter category. |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object. (Herdado de Object) |