2010-07-20 20 views
13

Mam niestandardową kategorię liczników, do której muszę dodać nowy licznik, bez usuwania ani resetowania żadnych istniejących liczników. Jak mogę to zrobić?Jak dodać nowy licznik do istniejącej kategorii liczników wydajności bez usuwania starych liczników?

Próbowałem użyć CounterExists(), ale nawet po utworzeniu licznika, jak mogę skojarzyć go z elementem CounterCreationDataCollection i powiązać go z mojej istniejącej kategorii licznika?

Odpowiedz

13

Najlepszym sposobem na to, co znalazłem, zwłaszcza, że ​​nie ma zbyt wielu informacji na ten temat, jest zachowanie istniejących wartości nieprzetworzonych, a następnie ponowne zastosowanie po usunięciu kategorii i ponownym utworzeniu. .

/// <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); 
    } 
} 
Powiązane problemy