13
我有一個自定義計數器類別,我需要添加一個新的計數器,而不刪除或重置任何現有的計數器。我怎樣才能做到這一點?如何在不刪除舊計數器的情況下將新計數器添加到現有的性能計數器類別?
我試過使用CounterExists(),但即使在創建計數器後,如何將其關聯到CounterCreationDataCollection項目並將其與現有的計數器類別關聯?
我有一個自定義計數器類別,我需要添加一個新的計數器,而不刪除或重置任何現有的計數器。我怎樣才能做到這一點?如何在不刪除舊計數器的情況下將新計數器添加到現有的性能計數器類別?
我試過使用CounterExists(),但即使在創建計數器後,如何將其關聯到CounterCreationDataCollection項目並將其與現有的計數器類別關聯?
做這件事的最好方法是找到了,特別是因爲似乎沒有太多關於這個主題的信息,所以保存現有的原始值,然後在刪除和重新創建類別後重新應用它們。
/// <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);
}
}