System.Diagnostics.PerformanceData Spazio dei nomi

Usare le classi in questo spazio dei nomi per fornire i dati del contatore. I contatori vengono usati per esporre ai consumatori la metrica delle prestazioni, ad esempio il monitoraggio delle prestazioni. Lo spazio dei nomi non contiene classi per l'utilizzo dei dati dei contatori. Per una descrizione completa dell'architettura dei contatori delle prestazioni, vedere Performance Counters (Contatori delle prestazioni).

Classi

CounterData

Contiene i dati non elaborati per un contatore.

CounterSet

Definisce un insieme di contatori logici.

CounterSetInstance

Crea un'istanza dei contatori logici definita nella classe CounterSet.

CounterSetInstanceCounterDataSet

Contiene l'insieme di valori del contatore.

Enumerazioni

CounterSetInstanceType

Specifica se l'insieme di contatori ammette istanze multiple, ad esempio processi e dischi fisici, o una singola istanza, ad esempio memoria.

CounterType

Definisce i possibili tipi di contatori. A ogni contatore viene assegnato un tipo di contatore. Il tipo di contatore determina come i dati dei contatori vengono calcolati, come se ne calcola la media e come vengono visualizzati.

Esempio

Di seguito è illustrato un semplice manifesto:

<!-- <?xml version="1.0" encoding="UTF-16"?> -->  
<instrumentationManifest xsi:schemaLocation="http://schemas.microsoft.com/win/2004/08/events eventman.xsd"   
     xmlns:win="http://manifests.microsoft.com/win/2004/08/windows/events"   
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
     xmlns:xs="http://www.w3.org/2001/XMLSchema"   
     xmlns:trace=http://schemas.microsoft.com/win/2004/08/events/trace>  

    <instrumentation>  

        <counters xmlns=http://schemas.microsoft.com/win/2005/12/counters>  

            <provider  
              applicationIdentity = "provider1.exe"  
              providerType = "userMode"  
              providerGuid = "{51D1685C-35ED-45be-99FE-17261A4F27F3}">  

               <counterSet guid = "{582803C9-AACD-45e5-8C30-571141A22092}"  
                  uri = "Microsoft.Windows.System.PerfCounters.Typing"  
                  name = "$(string.CounterSet1.Name)"   
                  description = "$(string.CounterSet1.Description)"   
                  instances = "single">  

                    <counter id = "1"  
                      uri = "Microsoft.Windows.System.PerfCounters.Typing.TotalWords"  
                      name = "$(string.CS1.Counter1.Name)"  
                      description = "$(string.CS1.Counter1.Description)"  
                      type = "perf_counter_rawcount"  
                      detailLevel = "standard"/>  

                    <counter id = "2"  
                      uri = "Microsoft.Windows.System.PerfCounters.Typing.WordsInInterval"  
                      name = "$(string.CS1.Counter2.Name)"  
                      description = "$(string.CS1.Counter2.Description)"  
                      type = "perf_counter_delta"  
                      detailLevel = "standard"/>  

                    <counter id = "3"  
                      uri = "Microsoft.Windows.System.PerfCounters.Typing.LetterAPressed"  
                      name = "$(string.CS1.Counter3.Name)"  
                      description = "$(string.CS1.Counter3.Description)"  
                      type = "perf_counter_rawcount"  
                      detailLevel = "standard"/>  

                    <counter id = "4"  
                      uri = "Microsoft.Windows.System.PerfCounters.Typing.WordsContainingLetterA"  
                      name = "$(string.CS1.Counter4.Name)"   
                      description = "$(string.CS1.Counter4.Description)"   
                      type = "perf_counter_rawcount"  
                      detailLevel = "standard"/>  

                    <counter id = "5"  
                      uri = "Microsoft.Windows.System.PerfCounters.Typing.PercentOfWordsContainingLetterA"  
                      name = "$(string.CS1.Counter5.Name)"   
                      description = "$(string.CS1.Counter5.Description)"   
                      type = "perf_sample_fraction"  
                      baseID = "6"  
                      detailLevel = "standard">  
                      <counterAttributes>  
                          <counterAttribute name = "displayAsReal" />  
                      </counterAttributes>  
                    </counter>  

                    <counter id = "6"  
                      uri = "Microsoft.Windows.System.PerfCounters.Typing.PercentBase"  
                      type = "perf_sample_base"  
                      detailLevel = "standard">  
                      <counterAttributes>  
                          <counterAttribute name = "noDisplay" />  
                      </counterAttributes>  
                    </counter>  

                </counterSet>  
            </provider>  
        </counters>  
    </instrumentation>  

    <localization>  
        <resources culture="en-US">  
            <stringTable>  

                <string id="CounterSet1.Name" value="Typing"/>  
                <string id="CounterSet1.Description" value="Captures simple typing metrics."/>  
                <string id="CS1.Counter1.Name" value="Total Words Typed"/>   
                <string id="CS1.Counter1.Description" value="The total number of words typed."/>  
                <string id="CS1.Counter2.Name" value="Words Typed In Interval"/>   
                <string id="CS1.Counter2.Description" value="The total number of words typed in the interval."/>  
                <string id="CS1.Counter3.Name" value="Letter A Pressed"/>   
                <string id="CS1.Counter3.Description" value="The number of times that the letter A is pressed."/>  
                <string id="CS1.Counter4.Name" value="Words Containing A"/>   
                <string id="CS1.Counter4.Description" value="The number of words that contain the letter A."/>  
                <string id="CS1.Counter5.Name" value="Percent of Words Containing A"/>   
                <string id="CS1.Counter5.Description" value="The percent of words that contain the letter A in the last interval."/>  

            </stringTable>  
        </resources>  
    </localization>  
</instrumentationManifest>  

Di seguito viene illustrata una semplice implementazione del provider per il manifesto:

using System.Diagnostics.PerformanceData;  

        private static Guid providerId = new Guid("{51D1685C-35ED-45be-99FE-17261A4F27F3}");  
        private static Guid typingCounterSetId = new Guid("{582803C9-AACD-45e5-8C30-571141A22092}");  

        private static CounterSet typingCounterSet;         // Defines the counter set  
        private static CounterSetInstance typingCsInstance; // Instance of the counter set  

        private static int numberOfLetterAInWord = 0;  

        . . .  

            // Create the 'Typing' counter set.  
            typingCounterSet = new CounterSet(providerId, typingCounterSetId, CounterSetInstanceType.Single);  

            // Add the counters to the counter set definition.  
            typingCounterSet.AddCounter(1, CounterType.RawData32, "Total Word Count");  
            typingCounterSet.AddCounter(2, CounterType.Delta32, "Words Typed In Interval");  
            typingCounterSet.AddCounter(3, CounterType.RawData32, "A Key Pressed");  
            typingCounterSet.AddCounter(4, CounterType.RawData32, "Words Containing A");  
            typingCounterSet.AddCounter(5, CounterType.SampleFraction, "Percent of Words Containing A");  
            typingCounterSet.AddCounter(6, CounterType.SampleBase, "Percent Base");  

            // Create an instance of the counter set (contains the counter data).  
            typingCsInstance = typingCounterSet.CreateCounterSetInstance("Typing Instance");  
            typingCsInstance.Counters[1].Value = 0;  
            typingCsInstance.Counters[2].Value = 0;  
            typingCsInstance.Counters[3].Value = 0;  
            typingCsInstance.Counters[4].Value = 0;  
            typingCsInstance.Counters[5].Value = 0;  
            typingCsInstance.Counters[6].Value = 0;  

        . . .  

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)  
        {  
            typingCounterSet.Dispose();  
        }  

        // Simple effort to capture letter A key press and words typed.  
        private void textInput_KeyDown(object sender, KeyEventArgs e)  
        {  
            Keys keyData = e.KeyData;  

            switch (e.KeyData)  
            {  
                case Keys.A :  
                    // In the .NET 3.5 Framework, you had to use the
                    // Value property to set and increment the counter   
                    // value. Beginning with the .NET 4.0 Framework,   
                    // the Value property is safe to use in a multi-  
                    // threaded application.  
                    typingCsInstance.Counters["A Key Pressed"].Value++;  
                    numberOfLetterAInWord++;  

                    break;  

                case Keys.Enter:  
                case Keys.Space:  
                case Keys.Tab:  

                    if (numberOfLetterAInWord > 0)  
                    {  
                        // Beginning with the .NET 4.0 Framework, you   
                        // can use the Increment method to increment   
                        // the counter value by 1. The Increment method   
                        // is safe to use in a multi-threaded   
                        // application.  
                        typingCsInstance.Counters["Words Containing A"].Increment();  
                        typingCsInstance.Counters["Percent of Words Containing A"].Increment();  
                        numberOfLetterAInWord = 0;  
                    }  

                    typingCsInstance.Counters["Percent Base"].Increment();  
                    typingCsInstance.Counters["Total Word Count"].Increment();  
                    typingCsInstance.Counters["Words Typed In Interval"].Increment();  

                    break;  
            }  
        }  

Commenti

Le classi in questo spazio dei nomi supportano la nuova architettura (versione 2.0) per i contatori delle prestazioni introdotti in Windows Vista. Nella nuova architettura il provider non risponde più direttamente alle richieste degli utenti, ma mantiene semplicemente i dati del contatore. Il sistema inserisce un thread nel processo del provider quando il provider crea un'istanza del set di contatori; il thread è responsabile della gestione delle richieste degli utenti.

I passaggi seguenti illustrano il processo di scrittura di un provider di contatori.

  1. I contatori forniti dal provider sono definiti in un manifesto basato su XML. I contatori vengono raggruppati logicamente in insiemi di contatori. I contatori all'interno di un set di contatori sono identificati da un identificatore numerico univoco all'interno del set di contatori. Un provider può definire uno o più insiemi di contatori. Un insieme di contatori è identificato da un GUID univoco per un provider. Si noti che se si usano queste classi per scrivere il provider:

    • L'attributo di callback dell'elemento del provider viene ignorato.

    • Il valore di riferimento per l'attributo name dell'elemento counterAttribute viene ignorato.

    Per informazioni dettagliate sulla scrittura del manifesto, vedere Schema dei contatori delle prestazioni.

  2. Dopo aver scritto il manifesto, usare lo strumento CTRPP per compilare il manifesto (ctrpp provider.man). Lo strumento genera quattro file: .h, .c, .rc e *_r.h. È possibile ignorare i file con estensione h e c. Il file RC contiene le stringhe localizzate definite nel manifesto. Usare i file rc e *_r.h per creare il file di risorse compilato (con estensione res) incluso nel progetto. La chiamata seguente illustra come compilare il file di risorse:

    rc /r /i "c:\Program Files\Microsoft SDKs\Windows\v6.0\Include" provider.rc  
    

    Se viene visualizzato un errore che fa riferimento a sal.h, copiare il file sal.h dal Microsoft Visual Studio, visual C include directory nella directory specificata per l'opzione /i.

    Aggiungere un percorso al file di risorse compilato (con estensione res) alla pagina delle proprietà Application del progetto.

  3. Scrivere il provider. I passaggi seguenti illustrano le chiamate effettuate da un provider:

    1. Chiamare il CounterSet.CounterSet costruttore per definire il set di contatori. Chiamare questo metodo per ogni set di contatori definito nel manifesto.

    2. Per ogni set di contatori, chiamare uno dei CounterSet.AddCounter metodi per aggiungere i contatori al set. Chiamare questo metodo per ogni contatore definito nel set di contatori.

    3. Chiamare il CounterSet.CreateCounterSetInstance metodo per creare un'istanza del set di contatori (un'istanza contiene i dati del contatore). Per i set di contatori a istanza singola, chiamare questo metodo una volta. Per più insiemi di contatori di istanze, chiamare questo metodo per ogni istanza per cui è necessario fornire i dati dei contatori (usare un nome univoco per ogni istanza).

    4. Utilizzare la CounterSetInstance.Counters proprietà per accedere e impostare i dati del contatore per il contatore.

  4. Al termine del provider, usare lo strumento LodCtr per registrare i contatori nel computer. Ad esempio,

    lodctr /m:provider.man  
    

    Nell'esempio si presuppone che il manifesto e il file eseguibile si trovino nella directory corrente.

È possibile usare le classi in questo spazio dei nomi nei computer che eseguono Windows Vista e sistemi operativi successivi.