You use the CounterSample class to create samples and perform calculations on their contents. A sample class performs a "sampling" of a performance counter based on criteria you define. These criteria include the values from one or more counters and the frequency with which values should be provided. In addition, the class records the time at which samples were taken. You can collect all of this data in a single instantiated class and then use the Calculate method to perform a calculation. You can also use the Calculate method to perform a calculation that compares values in two different samples.
The calculation performed depends on the type of the counters; certain counter types have specific calculations associated with them. For example, counters of the type ElapsedTime compare the time stamp on two different samples and determine how much time has elapsed. Many counters perform an averaging calculation based on the data retrieved.
These are the steps you go through to define a sample:
To retrieve performance counter samples
To perform calculations with retrieved samples
Note The two samples must be from counters of the same type or the method will throw an exception. The type of counter determines what kind of calculation performed. For more information, see Performance Counter Types.
The following code illustrates how to retrieve two samples and compare them using the Calculate method:
[Visual Basic] Dim sample1 as CounterSample Dim sample2 as CounterSample Dim result as single sample1 = PerformanceCounter1.NextSample() 'wait some interval of time here sample2 = PerformanceCounter1.NextSample() result = CounterSample.Calculate(sample1, sample2) [C#] CounterSample sample1 = new CounterSample(); CounterSample sample2 = new CounterSample(); single result; sample1 = PerformanceCounter1.NextSample(); // wait some interval of time here sample2 = PerformanceCounter1.NextSample(); result = CounterSample.Calculate(sample1, sample2);
Alternatively, you can call the NextSample method to provide the values for the second sample. The following example illustrates using this approach:
[Visual Basic]
Dim sample1 as CounterSample
Dim result as single
sample1 = PerformanceCounter1.NextSample()
result = CounterSample.Calculate(sample1, PerformanceCounter1.NextSample())
[C#]
CounterSample sample1 = new CounterSample(); single result; sample1 = PerformanceCounter1.NextSample(); result = CounterSample.Calculate(sample1, PerformanceCounter1.NextSample());
Performance Counter Value Retrieval | Retrieving Raw Performance Counter Values | Retrieving Calculated Performance Counter Values | Retrieving All Counters in a Category