CounterCreationDataCollection Clase
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Proporciona una colección fuertemente tipada de objetos CounterCreationData.
public ref class CounterCreationDataCollection : System::Collections::CollectionBase
public class CounterCreationDataCollection : System.Collections.CollectionBase
[System.Serializable]
public class CounterCreationDataCollection : System.Collections.CollectionBase
type CounterCreationDataCollection = class
inherit CollectionBase
[<System.Serializable>]
type CounterCreationDataCollection = class
inherit CollectionBase
Public Class CounterCreationDataCollection
Inherits CollectionBase
- Herencia
- Atributos
Ejemplos
En el siguiente ejemplo se muestra cómo utilizar la clase CounterCreationDataCollection. En el ejemplo se crea una nueva instancia de la clase y se usan varios métodos para agregar instrucciones a la colección, devolver su índice y agregar o quitar atributos en un punto de índice específico.
#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.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
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
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
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
'++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
' 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
End Class
Constructores
CounterCreationDataCollection() |
Inicializa una nueva instancia de la clase CounterCreationDataCollection sin instancias de CounterCreationData asociadas. |
CounterCreationDataCollection(CounterCreationData[]) |
Inicializa una instancia nueva de la clase CounterCreationDataCollection utilizando la matriz de instancias CounterCreationData especificada. |
CounterCreationDataCollection(CounterCreationDataCollection) |
Inicializa una nueva instancia de la clase CounterCreationDataCollection utilizando la colección especificada de instancias de CounterCreationData. |
Propiedades
Capacity |
Obtiene o establece el número de elementos que puede contener CollectionBase. (Heredado de CollectionBase) |
Count |
Obtiene el número de elementos contenidos en la instancia de CollectionBase. Esta propiedad no se puede invalidar. (Heredado de CollectionBase) |
InnerList |
Obtiene una colección ArrayList que contiene la lista de elementos incluidos en la instancia de CollectionBase. (Heredado de CollectionBase) |
Item[Int32] |
Indiza la colección CounterCreationData. |
List |
Obtiene una colección IList que contiene la lista de elementos incluidos en la instancia de CollectionBase. (Heredado de CollectionBase) |
Métodos
Add(CounterCreationData) |
Agrega una instancia de la clase CounterCreationData a la colección. |
AddRange(CounterCreationData[]) |
Agrega a la colección la matriz especificada de instancias de CounterCreationData. |
AddRange(CounterCreationDataCollection) |
Agrega a la colección la colección especificada de instancias de CounterCreationData. |
Clear() |
Elimina todos los objetos de la instancia de CollectionBase. Este método no se puede invalidar. (Heredado de CollectionBase) |
Contains(CounterCreationData) |
Determina si una instancia de CounterCreationData existe en la colección. |
CopyTo(CounterCreationData[], Int32) |
Copia los elementos de CounterCreationData en una matriz, empezando por el índice especificado de la matriz. |
Equals(Object) |
Determina si el objeto especificado es igual que el objeto actual. (Heredado de Object) |
GetEnumerator() |
Devuelve un enumerador que recorre en iteración la instancia de CollectionBase. (Heredado de CollectionBase) |
GetHashCode() |
Sirve como la función hash predeterminada. (Heredado de Object) |
GetType() |
Obtiene el Type de la instancia actual. (Heredado de Object) |
IndexOf(CounterCreationData) |
Devuelve el índice de un objeto CounterCreationData de la colección. |
Insert(Int32, CounterCreationData) |
Inserta un objeto CounterCreationData en la colección, en el índice especificado. |
MemberwiseClone() |
Crea una copia superficial del Object actual. (Heredado de Object) |
OnClear() |
Realiza procesos personalizados adicionales al borrar el contenido de la instancia CollectionBase. (Heredado de CollectionBase) |
OnClearComplete() |
Realiza procesos personalizados adicionales después de borrar el contenido de la instancia de CollectionBase. (Heredado de CollectionBase) |
OnInsert(Int32, Object) |
Esta API admite la infraestructura de producto y no está pensada para usarse directamente en el código. Lleva a cabo procesos personalizados adicionales antes de que se inserte una nueva entrada de datos en la colección. |
OnInsert(Int32, Object) |
Realiza procesos personalizados adicionales antes de insertar un nuevo elemento en la instancia de CollectionBase. (Heredado de CollectionBase) |
OnInsertComplete(Int32, Object) |
Realiza procesos personalizados adicionales después de insertar un nuevo elemento en la instancia de CollectionBase. (Heredado de CollectionBase) |
OnRemove(Int32, Object) |
Realiza procesos de personalización adicionales al quitar un elemento de la instancia de CollectionBase. (Heredado de CollectionBase) |
OnRemoveComplete(Int32, Object) |
Realiza procesos personalizados adicionales después de quitar un elemento de la instancia de CollectionBase. (Heredado de CollectionBase) |
OnSet(Int32, Object, Object) |
Realiza procesos personalizados adicionales antes de establecer un valor en la instancia de CollectionBase. (Heredado de CollectionBase) |
OnSetComplete(Int32, Object, Object) |
Realiza procesos personalizados adicionales después de establecer un valor en la instancia de CollectionBase. (Heredado de CollectionBase) |
OnValidate(Object) |
Comprueba el objeto especificado para determinar si es un tipo de CounterCreationData válido. |
OnValidate(Object) |
Realiza procesos de personalización adicionales al validar un valor. (Heredado de CollectionBase) |
Remove(CounterCreationData) |
Quita un objeto CounterCreationData de la colección. |
RemoveAt(Int32) |
Quita el elemento que se encuentra en el índice especificado de la instancia de CollectionBase. Este método no se puede reemplazar. (Heredado de CollectionBase) |
ToString() |
Devuelve una cadena que representa el objeto actual. (Heredado de Object) |
Implementaciones de interfaz explícitas
ICollection.CopyTo(Array, Int32) |
Copia la totalidad de CollectionBase en una matriz Array unidimensional compatible, comenzando en el índice especificado de la matriz de destino. (Heredado de CollectionBase) |
ICollection.IsSynchronized |
Obtiene un valor que indica si el acceso a la interfaz CollectionBase está sincronizado (es seguro para subprocesos). (Heredado de CollectionBase) |
ICollection.SyncRoot |
Obtiene un objeto que se puede usar para sincronizar el acceso a CollectionBase. (Heredado de CollectionBase) |
IList.Add(Object) |
Agrega un objeto al final de CollectionBase. (Heredado de CollectionBase) |
IList.Contains(Object) |
Determina si CollectionBase contiene un elemento específico. (Heredado de CollectionBase) |
IList.IndexOf(Object) |
Busca el objeto Object especificado y devuelve el índice de base cero de la primera aparición en toda la colección CollectionBase. (Heredado de CollectionBase) |
IList.Insert(Int32, Object) |
Inserta un elemento en CollectionBase en el índice especificado. (Heredado de CollectionBase) |
IList.IsFixedSize |
Obtiene un valor que indica si la interfaz CollectionBase tiene un tamaño fijo. (Heredado de CollectionBase) |
IList.IsReadOnly |
Obtiene un valor que indica si CollectionBase es de solo lectura. (Heredado de CollectionBase) |
IList.Item[Int32] |
Obtiene o establece el elemento en el índice especificado. (Heredado de CollectionBase) |
IList.Remove(Object) |
Quita la primera aparición de un objeto específico de la interfaz CollectionBase. (Heredado de CollectionBase) |
Métodos de extensión
Cast<TResult>(IEnumerable) |
Convierte los elementos de IEnumerable en el tipo especificado. |
OfType<TResult>(IEnumerable) |
Filtra los elementos de IEnumerable en función de un tipo especificado. |
AsParallel(IEnumerable) |
Habilita la paralelización de una consulta. |
AsQueryable(IEnumerable) |
Convierte una interfaz IEnumerable en IQueryable. |