【发布时间】:2011-03-18 09:12:22
【问题描述】:
我有一个自定义计数器类别,我需要向其中添加一个新计数器,而无需删除或重置任何现有计数器。我怎样才能做到这一点?
我尝试使用 CounterExists(),但即使在我创建了计数器之后,我如何才能将其关联到 CounterCreationDataCollection 项并将其关联到我现有的计数器类别?
【问题讨论】:
标签: c# .net performancecounter
我有一个自定义计数器类别,我需要向其中添加一个新计数器,而无需删除或重置任何现有计数器。我怎样才能做到这一点?
我尝试使用 CounterExists(),但即使在我创建了计数器之后,我如何才能将其关联到 CounterCreationDataCollection 项并将其关联到我现有的计数器类别?
【问题讨论】:
标签: c# .net performancecounter
我发现最好的方法是保留现有的原始值,然后在删除并重新创建类别后重新应用它们,特别是因为似乎没有太多关于此主题的信息。
/// <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);
}
}
【讨论】: