PerformanceCounter PerformanceCounter PerformanceCounter PerformanceCounter Class

Definição

Representa um componente do contador de desempenho do Windows NT. Represents a Windows NT performance counter component.

public ref class PerformanceCounter sealed : System::ComponentModel::Component, System::ComponentModel::ISupportInitialize
public sealed class PerformanceCounter : System.ComponentModel.Component, System.ComponentModel.ISupportInitialize
type PerformanceCounter = class
    inherit Component
    interface ISupportInitialize
Public NotInheritable Class PerformanceCounter
Inherits Component
Implements ISupportInitialize
Herança
Implementações

Exemplos

O exemplo de código a seguir demonstra o uso do PerformanceCounter classe para criar e usar um AverageCount64 tipo de contador.The following code example demonstrates the use of the PerformanceCounter class to create and use an AverageCount64 counter type. O exemplo cria categorias, configura os contadores, coleta dados de contadores e chama o CounterSampleCalculator classe para interpretar os dados de contador de desempenho.The example creates categories, sets up counters, collects data from the counters, and calls the CounterSampleCalculator class to interpret the performance counter data. Os resultados intermediários e finais são exibidos na janela do console.The intermediate and final results are displayed in the console window. Para obter exemplos adicionais de outros tipos de contador de desempenho, consulte o PerformanceCounterType enumeração.For additional examples of other performance counter types, see the PerformanceCounterType enumeration.

#using <System.dll>

using namespace System;
using namespace System::Collections;
using namespace System::Collections::Specialized;
using namespace System::Diagnostics;

// Output information about the counter sample.
void OutputSample( CounterSample s )
{
   Console::WriteLine( "\r\n+++++++++++" );
   Console::WriteLine( "Sample values - \r\n" );
   Console::WriteLine( "   BaseValue        = {0}", s.BaseValue );
   Console::WriteLine( "   CounterFrequency = {0}", s.CounterFrequency );
   Console::WriteLine( "   CounterTimeStamp = {0}", s.CounterTimeStamp );
   Console::WriteLine( "   CounterType      = {0}", s.CounterType );
   Console::WriteLine( "   RawValue         = {0}", s.RawValue );
   Console::WriteLine( "   SystemFrequency  = {0}", s.SystemFrequency );
   Console::WriteLine( "   TimeStamp        = {0}", s.TimeStamp );
   Console::WriteLine( "   TimeStamp100nSec = {0}", s.TimeStamp100nSec );
   Console::WriteLine( "++++++++++++++++++++++" );
}

//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
//    Description - This counter type shows how many items are processed, on average,
//        during an operation. Counters of this type display a ratio of the items 
//        processed (such as bytes sent) to the number of operations completed. The  
//        ratio is calculated by comparing the number of items processed during the 
//        last interval to the number of operations completed during the last interval. 
// Generic type - Average
//      Formula - (N1 - N0) / (D1 - D0), where the numerator (N) represents the number 
//        of items processed during the last sample interval and the denominator (D) 
//        represents the number of operations completed during the last two sample 
//        intervals. 
//    Average (Nx - N0) / (Dx - D0)  
//    Example PhysicalDisk\ Avg. Disk Bytes/Transfer 
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
float MyComputeCounterValue( CounterSample s0, CounterSample s1 )
{
   float numerator = (float)s1.RawValue - (float)s0.RawValue;
   float denomenator = (float)s1.BaseValue - (float)s0.BaseValue;
   float counterValue = numerator / denomenator;
   return counterValue;
}

bool SetupCategory()
{
   if (  !PerformanceCounterCategory::Exists( "AverageCounter64SampleCategory" ) )
   {
      CounterCreationDataCollection^ CCDC = gcnew CounterCreationDataCollection;
      
      // Add the counter.
      CounterCreationData^ averageCount64 = gcnew CounterCreationData;
      averageCount64->CounterType = PerformanceCounterType::AverageCount64;
      averageCount64->CounterName = "AverageCounter64Sample";
      CCDC->Add( averageCount64 );
      
      // Add the base counter.
      CounterCreationData^ averageCount64Base = gcnew CounterCreationData;
      averageCount64Base->CounterType = PerformanceCounterType::AverageBase;
      averageCount64Base->CounterName = "AverageCounter64SampleBase";
      CCDC->Add( averageCount64Base );
      
      // Create the category.
      PerformanceCounterCategory::Create( "AverageCounter64SampleCategory", "Demonstrates usage of the AverageCounter64 performance counter type.", CCDC );
      return (true);
   }
   else
   {
      Console::WriteLine( "Category exists - AverageCounter64SampleCategory" );
      return (false);
   }
}

void CreateCounters( PerformanceCounter^% PC, PerformanceCounter^% BPC )
{
   
   // Create the counters.
   PC = gcnew PerformanceCounter( "AverageCounter64SampleCategory","AverageCounter64Sample",false );

   BPC = gcnew PerformanceCounter( "AverageCounter64SampleCategory","AverageCounter64SampleBase",false );
   PC->RawValue = 0;
   BPC->RawValue = 0;
}
void CollectSamples( ArrayList^ samplesList, PerformanceCounter^ PC, PerformanceCounter^ BPC )
{
   Random^ r = gcnew Random( DateTime::Now.Millisecond );

   // Loop for the samples.
   for ( int j = 0; j < 100; j++ )
   {
      int value = r->Next( 1, 10 );
      Console::Write( "{0} = {1}", j, value );
      PC->IncrementBy( value );
      BPC->Increment();
      if ( (j % 10) == 9 )
      {
         OutputSample( PC->NextSample() );
         samplesList->Add( PC->NextSample() );
      }
      else
            Console::WriteLine();
      System::Threading::Thread::Sleep( 50 );
   }
}

void CalculateResults( ArrayList^ samplesList )
{
   for ( int i = 0; i < (samplesList->Count - 1); i++ )
   {
      // Output the sample.
      OutputSample(  *safe_cast<CounterSample^>(samplesList[ i ]) );
      OutputSample(  *safe_cast<CounterSample^>(samplesList[ i + 1 ]) );
      
      // Use .NET to calculate the counter value.
      Console::WriteLine( ".NET computed counter value = {0}", CounterSampleCalculator::ComputeCounterValue(  *safe_cast<CounterSample^>(samplesList[ i ]),  *safe_cast<CounterSample^>(samplesList[ i + 1 ]) ) );
      
      // Calculate the counter value manually.
      Console::WriteLine( "My computed counter value = {0}", MyComputeCounterValue(  *safe_cast<CounterSample^>(samplesList[ i ]),  *safe_cast<CounterSample^>(samplesList[ i + 1 ]) ) );
   }
}

int main()
{
   ArrayList^ samplesList = gcnew ArrayList;
   PerformanceCounter^ PC;
   PerformanceCounter^ BPC;
   SetupCategory();
   CreateCounters( PC, BPC );
   CollectSamples( samplesList, PC, BPC );
   CalculateResults( samplesList );
}

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;

public class App {

    private static PerformanceCounter avgCounter64Sample;
    private static PerformanceCounter avgCounter64SampleBase;

    public static void Main()
    {
    
        ArrayList samplesList = new ArrayList();

        // If the category does not exist, create the category and exit.
        // Performance counters should not be created and immediately used.
        // There is a latency time to enable the counters, they should be created
        // prior to executing the application that uses the counters.
        // Execute this sample a second time to use the category.
        if (SetupCategory())
            return;
        CreateCounters();
        CollectSamples(samplesList);
        CalculateResults(samplesList);

    }

    private static bool SetupCategory()
    {
        if ( !PerformanceCounterCategory.Exists("AverageCounter64SampleCategory") ) 
        {

            CounterCreationDataCollection counterDataCollection = new CounterCreationDataCollection();

            // Add the counter.
            CounterCreationData averageCount64 = new CounterCreationData();
            averageCount64.CounterType = PerformanceCounterType.AverageCount64;
            averageCount64.CounterName = "AverageCounter64Sample";
            counterDataCollection.Add(averageCount64);

            // Add the base counter.
            CounterCreationData averageCount64Base = new CounterCreationData();
            averageCount64Base.CounterType = PerformanceCounterType.AverageBase;
            averageCount64Base.CounterName = "AverageCounter64SampleBase";
            counterDataCollection.Add(averageCount64Base);

            // Create the category.
            PerformanceCounterCategory.Create("AverageCounter64SampleCategory",
                "Demonstrates usage of the AverageCounter64 performance counter type.",
                PerformanceCounterCategoryType.SingleInstance, counterDataCollection);

            return(true);
        }
        else
        {
            Console.WriteLine("Category exists - AverageCounter64SampleCategory");
            return(false);
        }
    }

    private static void CreateCounters()
    {
        // Create the counters.

        avgCounter64Sample = new PerformanceCounter("AverageCounter64SampleCategory", 
            "AverageCounter64Sample", 
            false);


        avgCounter64SampleBase = new PerformanceCounter("AverageCounter64SampleCategory", 
            "AverageCounter64SampleBase", 
            false);

        avgCounter64Sample.RawValue=0;
        avgCounter64SampleBase.RawValue=0;
    }
    private static void CollectSamples(ArrayList samplesList)
    {

        Random r = new Random( DateTime.Now.Millisecond );

        // Loop for the samples.
        for (int j = 0; j < 100; j++) 
        {

            int value = r.Next(1, 10);
            Console.Write(j + " = " + value);

            avgCounter64Sample.IncrementBy(value);

            avgCounter64SampleBase.Increment();

            if ((j % 10) == 9) 
            {
                OutputSample(avgCounter64Sample.NextSample());
                samplesList.Add( avgCounter64Sample.NextSample() );
            }
            else
                Console.WriteLine();

            System.Threading.Thread.Sleep(50);
        }

    }

    private static void CalculateResults(ArrayList samplesList)
    {
        for(int i = 0; i < (samplesList.Count - 1); i++)
        {
            // Output the sample.
            OutputSample( (CounterSample)samplesList[i] );
            OutputSample( (CounterSample)samplesList[i+1] );

            // Use .NET to calculate the counter value.
            Console.WriteLine(".NET computed counter value = " +
                CounterSampleCalculator.ComputeCounterValue((CounterSample)samplesList[i],
                (CounterSample)samplesList[i+1]) );

            // Calculate the counter value manually.
            Console.WriteLine("My computed counter value = " + 
                MyComputeCounterValue((CounterSample)samplesList[i],
                (CounterSample)samplesList[i+1]) );

        }
    }

    //++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
    //    Description - This counter type shows how many items are processed, on average,
    //        during an operation. Counters of this type display a ratio of the items 
    //        processed (such as bytes sent) to the number of operations completed. The  
    //        ratio is calculated by comparing the number of items processed during the 
    //        last interval to the number of operations completed during the last interval. 
    // Generic type - Average
    //      Formula - (N1 - N0) / (D1 - D0), where the numerator (N) represents the number 
    //        of items processed during the last sample interval and the denominator (D) 
    //        represents the number of operations completed during the last two sample 
    //        intervals. 
    //    Average (Nx - N0) / (Dx - D0)  
    //    Example PhysicalDisk\ Avg. Disk Bytes/Transfer 
    //++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
    private static Single MyComputeCounterValue(CounterSample s0, CounterSample s1)
    {
        Single numerator = (Single)s1.RawValue - (Single)s0.RawValue;
        Single denomenator = (Single)s1.BaseValue - (Single)s0.BaseValue;
        Single counterValue = numerator / denomenator;
        return(counterValue);
    }

    // Output information about the counter sample.
    private static void OutputSample(CounterSample s)
    {
        Console.WriteLine("\r\n+++++++++++");
        Console.WriteLine("Sample values - \r\n");
        Console.WriteLine("   BaseValue        = " + s.BaseValue);
        Console.WriteLine("   CounterFrequency = " + s.CounterFrequency);
        Console.WriteLine("   CounterTimeStamp = " + s.CounterTimeStamp);
        Console.WriteLine("   CounterType      = " + s.CounterType);
        Console.WriteLine("   RawValue         = " + s.RawValue);
        Console.WriteLine("   SystemFrequency  = " + s.SystemFrequency);
        Console.WriteLine("   TimeStamp        = " + s.TimeStamp);
        Console.WriteLine("   TimeStamp100nSec = " + s.TimeStamp100nSec);
        Console.WriteLine("++++++++++++++++++++++");
    }
}
Imports System
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Diagnostics

 _

Public Class App

    Private Shared avgCounter64Sample As PerformanceCounter
    Private Shared avgCounter64SampleBase As PerformanceCounter


    Public Shared Sub Main()

        Dim samplesList As New ArrayList()
        'If the category does not exist, create the category and exit.
        'Performance counters should not be created and immediately used.
        'There is a latency time to enable the counters, they should be created
        'prior to executing the application that uses the counters.
        'Execute this sample a second time to use the counters.
        If Not (SetupCategory()) Then
            CreateCounters()
            CollectSamples(samplesList)
            CalculateResults(samplesList)
        End If

    End Sub 'Main

    Private Shared Function SetupCategory() As Boolean
        If Not PerformanceCounterCategory.Exists("AverageCounter64SampleCategory") Then

            Dim counterDataCollection As New CounterCreationDataCollection()

            ' Add the counter.
            Dim averageCount64 As New CounterCreationData()
            averageCount64.CounterType = PerformanceCounterType.AverageCount64
            averageCount64.CounterName = "AverageCounter64Sample"
            counterDataCollection.Add(averageCount64)

            ' Add the base counter.
            Dim averageCount64Base As New CounterCreationData()
            averageCount64Base.CounterType = PerformanceCounterType.AverageBase
            averageCount64Base.CounterName = "AverageCounter64SampleBase"
            counterDataCollection.Add(averageCount64Base)

            ' Create the category.
            PerformanceCounterCategory.Create("AverageCounter64SampleCategory", _
               "Demonstrates usage of the AverageCounter64 performance counter type.", _
                      PerformanceCounterCategoryType.SingleInstance, counterDataCollection)

            Return True
        Else
            Console.WriteLine("Category exists - AverageCounter64SampleCategory")
            Return False
        End If
    End Function 'SetupCategory

    Private Shared Sub CreateCounters()
        ' Create the counters.

        avgCounter64Sample = New PerformanceCounter("AverageCounter64SampleCategory", "AverageCounter64Sample", False)

        avgCounter64SampleBase = New PerformanceCounter("AverageCounter64SampleCategory", "AverageCounter64SampleBase", False)

        avgCounter64Sample.RawValue = 0
        avgCounter64SampleBase.RawValue = 0
    End Sub 'CreateCounters

    Private Shared Sub CollectSamples(ByVal samplesList As ArrayList)

        Dim r As New Random(DateTime.Now.Millisecond)

        ' Loop for the samples.
        Dim j As Integer
        For j = 0 To 99

            Dim value As Integer = r.Next(1, 10)
            Console.Write(j.ToString() + " = " + value.ToString())

            avgCounter64Sample.IncrementBy(value)

            avgCounter64SampleBase.Increment()

            If j Mod 10 = 9 Then
                OutputSample(avgCounter64Sample.NextSample())
                samplesList.Add(avgCounter64Sample.NextSample())
            Else
                Console.WriteLine()
            End If
            System.Threading.Thread.Sleep(50)
        Next j
    End Sub 'CollectSamples

    Private Shared Sub CalculateResults(ByVal samplesList As ArrayList)
        Dim i As Integer
        For i = 0 To (samplesList.Count - 1) - 1
            ' Output the sample.
            OutputSample(CType(samplesList(i), CounterSample))
            OutputSample(CType(samplesList((i + 1)), CounterSample))

            ' Use .NET to calculate the counter value.
            Console.WriteLine(".NET computed counter value = " + CounterSampleCalculator.ComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample)).ToString())

            ' Calculate the counter value manually.
            Console.WriteLine("My computed counter value = " + MyComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample)).ToString())
        Next i
    End Sub 'CalculateResults

    '++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
    '	Description - This counter type shows how many items are processed, on average,
    '		during an operation. Counters of this type display a ratio of the items 
    '		processed (such as bytes sent) to the number of operations completed. The  
    '		ratio is calculated by comparing the number of items processed during the 
    '		last interval to the number of operations completed during the last interval. 
    ' Generic type - Average
    '  	Formula - (N1 - N0) / (D1 - D0), where the numerator (N) represents the number 
    '		of items processed during the last sample interval and the denominator (D) 
    '		represents the number of operations completed during the last two sample 
    '		intervals. 
    '	Average (Nx - N0) / (Dx - D0)  
    '	Example PhysicalDisk\ Avg. Disk Bytes/Transfer 
    '++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
    Private Shared Function MyComputeCounterValue(ByVal s0 As CounterSample, ByVal s1 As CounterSample) As [Single]
        Dim numerator As [Single] = CType(s1.RawValue, [Single]) - CType(s0.RawValue, [Single])
        Dim denomenator As [Single] = CType(s1.BaseValue, [Single]) - CType(s0.BaseValue, [Single])
        Dim counterValue As [Single] = numerator / denomenator
        Return counterValue
    End Function 'MyComputeCounterValue

    ' Output information about the counter sample.
    Private Shared Sub OutputSample(ByVal s As CounterSample)
        Console.WriteLine(ControlChars.Lf + ControlChars.Cr + "+++++++++++")
        Console.WriteLine("Sample values - " + ControlChars.Lf + ControlChars.Cr)
        Console.WriteLine(("   BaseValue        = " + s.BaseValue.ToString()))
        Console.WriteLine(("   CounterFrequency = " + s.CounterFrequency.ToString()))
        Console.WriteLine(("   CounterTimeStamp = " + s.CounterTimeStamp.ToString()))
        Console.WriteLine(("   CounterType      = " + s.CounterType.ToString()))
        Console.WriteLine(("   RawValue         = " + s.RawValue.ToString()))
        Console.WriteLine(("   SystemFrequency  = " + s.SystemFrequency.ToString()))
        Console.WriteLine(("   TimeStamp        = " + s.TimeStamp.ToString()))
        Console.WriteLine(("   TimeStamp100nSec = " + s.TimeStamp100nSec.ToString()))
        Console.WriteLine("++++++++++++++++++++++")
    End Sub 'OutputSample
End Class 'App

Comentários

O PerformanceCounter componente pode ser usado para leitura existentes predefinidos ou contadores personalizados e publicar (gravação) desempenho dados de contadores personalizados.The PerformanceCounter component can be used for both reading existing predefined or custom counters and publishing (writing) performance data to custom counters.

Há vários contadores predefinidos, listados no Monitor de desempenho do Windows caixa de diálogo Adicionar contadores.There are numerous predefined counters listed in the Windows Performance Monitor's Add Counters dialog box. Para saber mais sobre os contadores de desempenho do .NET Framework, consulte contadores de desempenho.To learn about the .NET Framework performance counters, see Performance Counters.

Esse tipo implementa o IDisposable interface.This type implements the IDisposable interface. Quando você terminar de usar o tipo, você deve descartá-lo diretamente ou indiretamente.When you have finished using the type, you should dispose of it either directly or indirectly. Para descartar o tipo diretamente, chame seu Dispose método em um try / catch bloco.To dispose of the type directly, call its Dispose method in a try/catch block. Para descartá-los indiretamente, usar uma construção de linguagem, como using (em c#) ou Using (no Visual Basic).To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). Para obter mais informações, consulte a seção "Usando um objeto que implementa IDisposable" o IDisposable tópico da interface.For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

Importante

Nas versões 1.0 e 1.1 do .NET Framework, essa classe requer imediatos chamadores sejam totalmente confiáveis.In versions 1.0 and 1.1 of the .NET Framework, this class requires immediate callers to be fully trusted. Começando com o .NET Framework versão 2.0, essa classe requer PerformanceCounterPermission para ações específicas.Starting with the .NET Framework version 2.0, this class requires PerformanceCounterPermission for specific actions. É altamente recomendável que PerformanceCounterPermission não ser concedidas ao código de confiança parcial.It is strongly recommended that PerformanceCounterPermission not be granted to semi-trusted code. A capacidade de ler e gravar contadores de desempenho permite que o código executar ações como a numeração de processos em execução e obtenção de informações sobre eles.The ability to read and write performance counters allows code to perform actions such as enumerating executing processes and obtaining information about them.

Além disso, passando um PerformanceCounter objeto para código menos confiável pode criar um problema de segurança.In addition, passing a PerformanceCounter object to less-trusted code can create a security issue. Nunca passe desempenho objetos de contador, como uma PerformanceCounterCategory ou PerformanceCounter, para que o código menos confiável.Never pass performance counter objects, such as a PerformanceCounterCategory or PerformanceCounter, to less trusted code.

Para ler de um contador de desempenho, crie uma instância das PerformanceCounter classe, defina o CategoryName, CounterNamee, opcionalmente, o InstanceName ou MachineName propriedades e, em seguida, chamar o NextValue método tenham um desempenho leitor do contador.To read from a performance counter, create an instance of the PerformanceCounter class, set the CategoryName, CounterName, and, optionally, the InstanceName or MachineName properties, and then call the NextValue method to take a performance counter reading.

Para publicar dados do contador de desempenho, crie um ou mais contadores personalizados usando o PerformanceCounterCategory.Create método, crie uma instância da PerformanceCounter classe, defina o CategoryName, CounterName e, opcionalmente, InstanceName ou MachineName propriedades, e, em seguida, chame o IncrementBy, Increment, ou Decrement métodos ou conjunto de RawValue propriedade para alterar o valor do contador personalizado.To publish performance counter data, create one or more custom counters using the PerformanceCounterCategory.Create method, create an instance of the PerformanceCounter class, set the CategoryName, CounterName and, optionally, InstanceName or MachineName properties, and then call the IncrementBy, Increment, or Decrement methods, or set the RawValue property to change the value of your custom counter.

Observação

O Increment, IncrementBy, e Decrement métodos usam travas para atualizar o valor do contador.The Increment, IncrementBy, and Decrement methods use interlocks to update the counter value. Isso ajuda a manter o valor do contador precisos em cenários multi-threaded ou multiprocesso, mas também resulta em uma penalidade de desempenho.This helps keep the counter value accurate in multithreaded or multiprocess scenarios, but also results in a performance penalty. Se você não precisar da precisão que interligado operações fornecem, você pode atualizar o RawValue propriedade diretamente para até 5 vezes a melhoria de desempenho.If you do not need the accuracy that interlocked operations provide, you can update the RawValue property directly for up to a 5 times performance improvement. No entanto, em cenários com vários threads, algumas atualizações para o valor do contador podem ser ignoradas, resultando em dados imprecisos.However, in multithreaded scenarios, some updates to the counter value might be ignored, resulting in inaccurate data.

O contador é o mecanismo pelo qual o desempenho, os dados são coletados.The counter is the mechanism by which performance data is collected. O registro armazena os nomes de todos os contadores, cada uma delas está relacionada a uma área específica da funcionalidade do sistema.The registry stores the names of all the counters, each of which is related to a specific area of system functionality. Exemplos incluem o tempo de ocupação do processador, o uso de memória ou o número de bytes recebidos em uma conexão de rede.Examples include a processor's busy time, memory usage, or the number of bytes received over a network connection.

Cada contador é identificada exclusivamente por meio de seu nome e sua localização.Each counter is uniquely identified through its name and its location. Da mesma forma que um caminho de arquivo inclui uma unidade, um diretório, um ou mais subdiretórios e um nome de arquivo, informações do contador consistem em quatro elementos: o computador, a categoria, a instância da categoria e o nome do contador.In the same way that a file path includes a drive, a directory, one or more subdirectories, and a file name, counter information consists of four elements: the computer, the category, the category instance, and the counter name.

As informações do contador devem incluir a categoria, ou o objeto de desempenho que mede a dados para o contador.The counter information must include the category, or performance object, that the counter measures data for. Categorias de um computador incluem componentes físicos, como memória, discos e processadores.A computer's categories include physical components, such as processors, disks, and memory. Também há categorias de sistema, como processos e threads.There are also system categories, such as processes and threads. Cada categoria está relacionada a um elemento funcional no computador e tem um conjunto de contadores padrão atribuído a ele.Each category is related to a functional element within the computer and has a set of standard counters assigned to it. Esses objetos são listados na lista suspensa de objeto de desempenho da caixa de diálogo Adicionar contadores no Monitor do sistema do Windows 2000, e você deve incluí-las no caminho do contador.These objects are listed in the Performance object drop-down list of the Add Counters dialog box within the Windows 2000 System Monitor, and you must include them in the counter path. Dados de desempenho são agrupados pela categoria à qual é relacionado.Performance data is grouped by the category to which is it related.

Em alguns casos, várias cópias da mesma categoria podem existir.In certain cases, several copies of the same category can exist. Por exemplo, vários processos e threads executados simultaneamente, e alguns computadores contêm mais de um processador.For example, several processes and threads run simultaneously, and some computers contain more than one processor. As cópias de categoria são chamadas de instâncias de categoria, e cada instância tem um conjunto de contadores padrão atribuído a ele.The category copies are called category instances, and each instance has a set of standard counters assigned to it. Se uma categoria pode ter mais de uma instância, uma especificação de instância deve ser incluída nas informações do contador.If a category can have more than one instance, an instance specification must be included in the counter information.

Para obter dados de desempenho para contadores que são necessários um valor inicial ou anterior para realizar o cálculo necessário, chame o NextValue método duas vezes e use as informações retornadas como seu aplicativo requer.To obtain performance data for counters that required an initial or previous value for performing the necessary calculation, call the NextValue method twice and use the information returned as your application requires.

Observação

Categorias de contador de desempenho instaladas com o .NET Framework 2.0.NET Framework 2.0 usar 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.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 com a criação de um DWORD chamado FileMappingSize na chave do registro HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\<nome da categoria > \ Desempenho.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 de FileMappingSize é definido como o tamanho de memória compartilhada da categoria.The FileMappingSize value is set to the shared memory size of the category. O tamanho padrão será 131072 decimal.The default size is 131072 decimal. Se o valor de FileMappingSize não estiver presente, o fileMappingSize valor de atributo a performanceCounters elemento especificado no arquivo Machine. config é usado, causando uma 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 de inicialização do aplicativo, definindo o tamanho do mapeamento de 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

PerformanceCounter() PerformanceCounter() PerformanceCounter() PerformanceCounter()

Inicializa uma nova instância somente leitura da classe PerformanceCounter, sem associar a instância a nenhum sistema ou contador de desempenho personalizado. Initializes a new, read-only instance of the PerformanceCounter class, without associating the instance with any system or custom performance counter.

PerformanceCounter(String, String) PerformanceCounter(String, String) PerformanceCounter(String, String) PerformanceCounter(String, String)

Inicializa uma instância nova e somente leitura da classe PerformanceCounter e a associa ao contador de desempenho personalizado ou do sistema, especificado no computador local. Initializes a new, read-only instance of the PerformanceCounter class and associates it with the specified system or custom performance counter on the local computer. Este construtor requer que a categoria de tenha uma única instância. This constructor requires that the category have a single instance.

PerformanceCounter(String, String, Boolean) PerformanceCounter(String, String, Boolean) PerformanceCounter(String, String, Boolean) PerformanceCounter(String, String, Boolean)

Inicializa uma instância nova e somente leitura ou de leitura/gravação da classe PerformanceCounter e a associa ao contador de desempenho personalizado ou do sistema especificado no computador local. Initializes a new, read-only or read/write instance of the PerformanceCounter class and associates it with the specified system or custom performance counter on the local computer. Este construtor requer que a categoria contenha uma única instância. This constructor requires that the category contain a single instance.

PerformanceCounter(String, String, String) PerformanceCounter(String, String, String) PerformanceCounter(String, String, String) PerformanceCounter(String, String, String)

Inicializa uma instância nova e somente leitura da classe PerformanceCounter e a associa ao sistema especificado ou ao contador de desempenho personalizado e à instância de categoria no computador local. Initializes a new, read-only instance of the PerformanceCounter class and associates it with the specified system or custom performance counter and category instance on the local computer.

PerformanceCounter(String, String, String, Boolean) PerformanceCounter(String, String, String, Boolean) PerformanceCounter(String, String, String, Boolean) PerformanceCounter(String, String, String, Boolean)

Inicializa uma instância nova e somente leitura ou de leitura/gravação da classe PerformanceCounter e a associa ao sistema especificado ou ao contador de desempenho personalizado e à instância de categoria no computador local. Initializes a new, read-only or read/write instance of the PerformanceCounter class and associates it with the specified system or custom performance counter and category instance on the local computer.

PerformanceCounter(String, String, String, String) PerformanceCounter(String, String, String, String) PerformanceCounter(String, String, String, String) PerformanceCounter(String, String, String, String)

Inicializa uma instância nova e somente leitura da classe PerformanceCounter e a associa ao sistema especificado ou ao contador de desempenho personalizado e à instância de categoria no computador especificado. Initializes a new, read-only instance of the PerformanceCounter class and associates it with the specified system or custom performance counter and category instance, on the specified computer.

Campos

DefaultFileMappingSize DefaultFileMappingSize DefaultFileMappingSize DefaultFileMappingSize

Especifica o tamanho, em bytes, da memória global compartilhada pelos contadores de desempenho. Specifies the size, in bytes, of the global memory shared by performance counters. O tamanho padrão é de 524.288 bytes. The default size is 524,288 bytes.

Propriedades

CanRaiseEvents CanRaiseEvents CanRaiseEvents CanRaiseEvents

Obtém um valor que indica se o componente pode acionar um evento. Gets a value indicating whether the component can raise an event.

(Inherited from Component)
CategoryName CategoryName CategoryName CategoryName

Obtém ou define o nome da categoria do contador de desempenho desse contador de desempenho. Gets or sets the name of the performance counter category for this performance counter.

Container Container Container Container

Obtém o IContainer que contém o Component. Gets the IContainer that contains the Component.

(Inherited from Component)
CounterHelp CounterHelp CounterHelp CounterHelp

Obtém a descrição para este contador de desempenho. Gets the description for this performance counter.

CounterName CounterName CounterName CounterName

Obtém ou define o nome do contador de desempenho associado a esta instância PerformanceCounter. Gets or sets the name of the performance counter that is associated with this PerformanceCounter instance.

CounterType CounterType CounterType CounterType

Obtém o tipo do contador de desempenho associado. Gets the counter type of the associated performance counter.

DesignMode DesignMode DesignMode DesignMode

Obtém um valor que indica se o Component está no modo de design no momento. Gets a value that indicates whether the Component is currently in design mode.

(Inherited from Component)
Events Events Events Events

Obtém a lista de manipuladores de eventos que estão anexados a este Component. Gets the list of event handlers that are attached to this Component.

(Inherited from Component)
InstanceLifetime InstanceLifetime InstanceLifetime InstanceLifetime

Obtém ou define o tempo de vida de um processo. Gets or sets the lifetime of a process.

InstanceName InstanceName InstanceName InstanceName

Obtém ou define um nome de instância para o contador de desempenho. Gets or sets an instance name for this performance counter.

MachineName MachineName MachineName MachineName

Obtém ou define um nome do computador para esse contador de desempenho Gets or sets the computer name for this performance counter

RawValue RawValue RawValue RawValue

Obtém ou define o valor bruto, ou não calculado, desse contador. Gets or sets the raw, or uncalculated, value of this counter.

ReadOnly ReadOnly ReadOnly ReadOnly

Obtém ou define um valor que indica se esta instância PerformanceCounter está no modo somente leitura. Gets or sets a value indicating whether this PerformanceCounter instance is in read-only mode.

Site Site Site Site

Obtém ou define o ISite do Component. Gets or sets the ISite of the Component.

(Inherited from Component)

Métodos

BeginInit() BeginInit() BeginInit() BeginInit()

Começa a inicialização de uma instância PerformanceCounter usada em um formulário ou por outro componente. Begins the initialization of a PerformanceCounter instance used on a form or by another component. A inicialização ocorre em tempo de execução. The initialization occurs at runtime.

Close() Close() Close() Close()

Fecha o contador de desempenho e libera todos os recursos alocados por esta instância do contador de desempenho. Closes the performance counter and frees all the resources allocated by this performance counter instance.

CloseSharedResources() CloseSharedResources() CloseSharedResources() CloseSharedResources()

Libera o estado compartilhado da biblioteca do contador de desempenho alocado pelos contadores. Frees the performance counter library shared state allocated by the counters.

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

Cria um objeto que contém todas as informações relevantes necessárias para gerar um proxy usado para se comunicar com um objeto remoto. Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Decrement() Decrement() Decrement() Decrement()

Decrementa em um o contador de desempenho associado por meio de uma operação atômica eficiente. Decrements the associated performance counter by one through an efficient atomic operation.

Dispose() Dispose() Dispose() Dispose()

Libera todos os recursos usados pelo Component. Releases all resources used by the Component.

(Inherited from Component)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

Libera os recursos não gerenciados usados pelo Component e opcionalmente libera os recursos gerenciados. Releases the unmanaged resources used by the Component and optionally releases the managed resources.

(Inherited from Component)
EndInit() EndInit() EndInit() EndInit()

Termina a inicialização de uma instância PerformanceCounter que é usada em um formulário ou por outro componente. Ends the initialization of a PerformanceCounter instance that is used on a form or by another component. A inicialização ocorre em tempo de execução. The initialization occurs at runtime.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina se o objeto especificado é igual ao objeto atual. Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Serve como a função de hash padrão. Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

Recupera o objeto de serviço de tempo de vida atual que controla a política de ciclo de vida para esta instância. Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetService(Type) GetService(Type) GetService(Type) GetService(Type)

Retorna um objeto que representa um serviço fornecido pelo Component ou pelo seu Container. Returns an object that represents a service provided by the Component or by its Container.

(Inherited from Component)
GetType() GetType() GetType() GetType()

Obtém o Type da instância atual. Gets the Type of the current instance.

(Inherited from Object)
Increment() Increment() Increment() Increment()

Incrementa em um o contador de desempenho associado através de uma operação atômica eficiente. Increments the associated performance counter by one through an efficient atomic operation.

IncrementBy(Int64) IncrementBy(Int64) IncrementBy(Int64) IncrementBy(Int64)

Incrementa ou diminui o valor do contador de desempenho associado em um valor especificado por meio de uma operação atômica eficiente. Increments or decrements the value of the associated performance counter by a specified amount through an efficient atomic operation.

InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

Obtém um objeto de serviço de tempo de vida para controlar a política de tempo de vida para essa instância. Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Cria uma cópia superficial do Object atual. Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

Cria uma cópia superficial do objeto MarshalByRefObject atual. Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
NextSample() NextSample() NextSample() NextSample()

Obtém uma amostra de contador e retorna o valor bruto ou não calculado para ela. Obtains a counter sample, and returns the raw, or uncalculated, value for it.

NextValue() NextValue() NextValue() NextValue()

Obtém uma amostra de contador e retorna o valor calculado para ela. Obtains a counter sample and returns the calculated value for it.

RemoveInstance() RemoveInstance() RemoveInstance() RemoveInstance()

Exclui a instância da categoria especificada pelo objeto PerformanceCounter, propriedade InstanceName. Deletes the category instance specified by the PerformanceCounter object InstanceName property.

ToString() ToString() ToString() ToString()

Retorna um String que contém o nome do Component, se houver. Returns a String containing the name of the Component, if any. Esse método não deve ser substituído. This method should not be overridden.

(Inherited from Component)

Eventos

Disposed Disposed Disposed Disposed

Ocorre quando o componente é disposto por uma chamada para o método Dispose(). Occurs when the component is disposed by a call to the Dispose() method.

(Inherited from Component)

Aplica-se a

Veja também