How to add a new counter to an existing performance counter category without deleting the old counters?

最后都变了- 提交于 2019-11-29 17:32:34

问题


I have a custom counter category, to which I need to add a new counter, without deleting or resetting any existing counters. How can I do this?

I tried using CounterExists(), but even after I create the counter, how can I associate it to a CounterCreationDataCollection item and associate it to my existing counter category?


回答1:


The best way to do this I found, especially since there doesn't seem to be much info on this topic, is to preserve the existing raw values and then re-apply them after the category is deleted and re-created.

/// <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);
    }
}


来源:https://stackoverflow.com/questions/3289242/how-to-add-a-new-counter-to-an-existing-performance-counter-category-without-del

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!