Represents a Windows NT performance counter component.
Assembly: System (in System.dll)
Thetype exposes the following members.
|PerformanceCounter||Initializes a new, read-only instance of the class, without associating the instance with any system or custom performance counter.|
|PerformanceCounter(String, String)||Initializes a new, read-only instance of the class and associates it with the specified system or custom performance counter on the local computer. This constructor requires that the category have a single instance.|
|PerformanceCounter(String, String, Boolean)||Initializes a new, read-only or read/write instance of the class and associates it with the specified system or custom performance counter on the local computer. This constructor requires that the category contain a single instance.|
|PerformanceCounter(String, String, String)||Initializes a new, read-only instance of the class and associates it with the specified system or custom performance counter and category instance on the local computer.|
|PerformanceCounter(String, String, String, Boolean)||Initializes a new, read-only or read/write instance of the class and associates it with the specified system or custom performance counter and category instance on the local computer.|
|PerformanceCounter(String, String, String, String)||Initializes a new, read-only instance of the class and associates it with the specified system or custom performance counter and category instance, on the specified computer.|
|CategoryName||Gets or sets the name of the performance counter category for this performance counter.|
|Container||Gets the IContainer that contains the Component. (Inherited from Component.)|
|CounterHelp||Gets the description for this performance counter.|
|CounterName||Gets or sets the name of the performance counter that is associated with this instance.|
|CounterType||Gets the counter type of the associated performance counter.|
|InstanceLifetime||Gets or sets the lifetime of a process.|
|InstanceName||Gets or sets an instance name for this performance counter.|
|MachineName||Gets or sets the computer name for this performance counter|
|RawValue||Gets or sets the raw, or uncalculated, value of this counter.|
|ReadOnly||Gets or sets a value indicating whether this instance is in read-only mode.|
|Site||Gets or sets the ISite of the Component. (Inherited from Component.)|
|BeginInit||Begins the initialization of a instance used on a form or by another component. The initialization occurs at runtime.|
|Close||Closes the performance counter and frees all the resources allocated by this performance counter instance.|
|CloseSharedResources||Frees the performance counter library shared state allocated by the counters.|
|CreateObjRef||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||Decrements the associated performance counter by one through an efficient atomic operation.|
|Dispose||Releases all resources used by the Component. (Inherited from Component.)|
|EndInit||Ends the initialization of a instance that is used on a form or by another component. The initialization occurs at runtime.|
|Equals(Object)||Determines whether the specified object is equal to the current object. (Inherited from Object.)|
|GetHashCode||Serves as the default hash function. (Inherited from Object.)|
|GetLifetimeService||Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)|
|GetType||Gets the Type of the current instance. (Inherited from Object.)|
|Increment||Increments the associated performance counter by one through an efficient atomic operation.|
|IncrementBy||Increments or decrements the value of the associated performance counter by a specified amount through an efficient atomic operation.|
|InitializeLifetimeService||Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)|
|NextSample||Obtains a counter sample, and returns the raw, or uncalculated, value for it.|
|NextValue||Obtains a counter sample and returns the calculated value for it.|
|RemoveInstance||Deletes the category instance specified by the object InstanceName property.|
|ToString||Returns a String containing the name of the Component, if any. This method should not be overridden. (Inherited from Component.)|
The component can be used for both reading existing predefined or custom counters and publishing (writing) performance data to custom counters.
In versions 1.0 and 1.1 of the .NET Framework, this class requires immediate callers to be fully trusted. Starting with the .NET Framework version 2.0, this class requires PerformanceCounterPermission for specific actions. It is strongly recommended that PerformanceCounterPermission not be granted to semi-trusted code. The ability to read and write performance counters allows code to perform actions such as enumerating executing processes and obtaining information about them.
Passing a object to less-trusted code can create a security issue. Never pass performance counter objects, such as a PerformanceCounterCategory or , to less trusted code.
The predefined counters are too numerous to mention. You can get a list of the available pre-existing counters from the Windows Performance Monitor's Add Counters dialog box. To learn about the .NET Framework performance counters, see Performance Counters in the .NET Framework.
To read from a performance counter, create an instance of the class, set the CategoryName, CounterName, and, optionally, the InstanceName or MachineName properties, and then call the NextValue method to take a performance counter reading.
To publish performance counter data, create one or more custom counters using the PerformanceCounterCategory.Create method, create an instance of the 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.
The Increment, IncrementBy, and Decrement methods use interlocks to update the counter value. This helps keep the counter value accurate in multithreaded or multiprocess scenarios, but also results in a performance penalty. 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. However, in multithreaded scenarios, some updates to the counter value might be ignored, resulting in inaccurate data.
The counter is the mechanism by which performance data is collected. The registry stores the names of all the counters, each of which is related to a specific area of system functionality. Examples include a processor's busy time, memory usage, or the number of bytes received over a network connection.
Each counter is uniquely identified through its name and its location. 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.
The counter information must include the category, or performance object, that the counter measures data for. A computer's categories include physical components, such as processors, disks, and memory. There are also system categories, such as processes and threads. Each category is related to a functional element within the computer and has a set of standard counters assigned to it. 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. Performance data is grouped by the category to which is it related.
In certain cases, several copies of the same category can exist. For example, several processes and threads run simultaneously, and some computers contain more than one processor. The category copies are called category instances, and each instance has a set of standard counters assigned to it. If a category can have more than one instance, an instance specification must be included in the counter information.
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.
Performance counter categories installed with the .NET Framework 2.0 use separate shared memory, with each performance counter category having its own memory. 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. The FileMappingSize value is set to the shared memory size of the category. The default size is 131072 decimal. 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. You can realize a performance improvement for application startup by setting the file mapping size in the registry. For more information about the file mapping size, see <performanceCounters> Element.
The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: Synchronization | SharedState. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.
Windows 98, Windows Millennium Edition Platform Note: Performance counters are not supported on Windows 98 or Windows Millennium Edition (Me).
The following code example demonstrates the use of the class to create and use an AverageCount64 counter type. The example creates categories, sets up counters, collects data from the counters, and calls the CounterSampleCalculator class to interpret the performance counter data. The intermediate and final results are displayed in the console window. For additional examples of other performance counter types, see the PerformanceCounterType enumeration.
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
Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.