2010-07-20 11 views
13

Ho una categoria contatore personalizzata, a cui ho bisogno di aggiungere un nuovo contatore, senza cancellare o reimpostare alcun contatore esistente. Come posso fare questo?Come aggiungere un nuovo contatore a una categoria di contatore delle prestazioni esistente senza eliminare i vecchi contatori?

Ho provato a usare CounterExists(), ma anche dopo aver creato il contatore, come posso associarlo a un oggetto CounterCreationDataCollection e associarlo alla mia categoria di contatore esistente?

risposta

13

Il modo migliore per farlo ho trovato, soprattutto perché non sembrano esserci molte informazioni su questo argomento, è quello di preservare i valori grezzi esistenti e quindi riapplicarli dopo che la categoria è stata cancellata e ricreata .

/// <summary> 
/// When deleting the Category, need to preserve the existing counter values 
/// </summary> 
static Dictionary<string, long> GetPreservedValues(string category, XmlNodeList nodes) 
{ 
    Dictionary<string, long> preservedValues = new Dictionary<string, long>(); 

    foreach (XmlNode counterNode in nodes) 
    { 
     string counterName = counterNode.Attributes["name"].Value; 

     if (PerformanceCounterCategory.CounterExists(counterName, category)) 
     { 
      PerformanceCounter performanceCounter = new PerformanceCounter(category, counterName, false); 
      preservedValues.Add(counterName, performanceCounter.RawValue); 

      Console.WriteLine("Preserving {0} with a RawValue of {1}", counterName, performanceCounter.RawValue); 
     } 
     else 
     { 
      Console.WriteLine("Unable to preserve {0} because it doesn't exist", counterName); 
     } 
    } 

    return preservedValues; 
} 

/// <summary> 
/// Restore preserved values after the category has been re-created 
/// </summary> 
static void SetPreservedValues(string category, Dictionary<string, long> preservedValues) 
{ 
    foreach (KeyValuePair<string, long> preservedValue in preservedValues) 
    { 
     PerformanceCounter performanceCounter = new PerformanceCounter(category, preservedValue.Key, false); 
     performanceCounter.RawValue = preservedValue.Value; 

     Console.WriteLine("Restoring {0} with a RawValue of {1}", preservedValue.Key, performanceCounter.RawValue); 
    } 
} 
Problemi correlati