为什么我的性能计数器不会改变?

2024-04-25

我一定在这里做错了什么。我创建了一个自定义性能计数器,如下所示:

string counterCategory = "Test Category";
string counterName = "Test Counter";

if (!PerformanceCounterCategory.Exists(counterCategory))
{
    Console.WriteLine("Creating Counters");

    CounterCreationDataCollection counterCreationDataCollection =
        new CounterCreationDataCollection();

    counterCreationDataCollection.Add(
        new CounterCreationData(counterName,
        "Description",
        PerformanceCounterType.NumberOfItems32)
    );

    PerformanceCounterCategory.Create(counterCategory,
        "My category description/Help",
        PerformanceCounterCategoryType.SingleInstance,
        counterCreationDataCollection);
}

计数器类别和计数器已创建并可在性能监视器中查看。

然后我尝试更改计数器的值

PerformanceCounter myCounter = 
    new PerformanceCounter(counterCategory, counterName, false);

for (int i = 0; i < 10; i++)
{
    Console.WriteLine("Setting to "+i);
    myCounter.RawValue = i;
    Thread.Sleep(200);
}

myCounter.Close();

然而,当我坐下来观察性能监视器中的计数器时,没有任何反应,该值永远不会改变。

那么我做错了什么?

如果我添加对 nextValue() 或 rawValue() 的调用,则该值将按我的预期返回,但 Windows 性能监视器仍然显示一条平线,例如

for (int i = 0; i < 10; i++)
{
    Console.WriteLine("Setting to "+i);
    myCounter.IncrementValue()
    Console.WriteLine("Next Value = "+myCounter.RawValue()); 
    Thread.Sleep(200);
}

Edit:我发现如果我关闭性能监视器然后重新打开它而不删除计数器,它会突然意识到有一个新值。因此,这些值正在设置并保留,但性能监视器看不到更改。


后续行动已有序进行。无论如何,在Win7下,性能监视器似乎可能无法按预期工作。当我编写测试代码时,我在创建计数器后暂停了应用程序,以便启动性能监视器。一旦我让它继续,监视器就不会改变它的计数器,尽管底层计数器被改变了。

如果我随后退出性能监视器并重新启动它,则会显示测试程序中的最后一个计数器值,表明其设置正确。如果我再次运行测试程序,仅更改值,性能监视器最终会发现更改。

因此,正如每个人都指出的那样,代码是正确的,是 Windows 性能监视器出现了异常。

谢谢大家的答案!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么我的性能计数器不会改变? 的相关文章

随机推荐